简体   繁体   English

如何将 txt 文件中的行分组到嵌套字典(Python)

[英]How to group the line in txt file to nested dictionary (Python)

I have a txt file that contain the data as below:我有一个包含以下数据的 txt 文件:

Id_1 1111
Member_a 2222
Member_b 3333
Member_c 4444
Device_a 5555
Device_b 6666

Id_2 1234
Member_a 5678
Member_b 1345
Device_a 3141

Id_3 1317
Member_a 5643
Member_b 4678
Member_c 4654
Member_e 4674
member_f 2314
Device_a 4433
Device_b 4354

.
.
.

and so on

There are 3 fields contained in each id and each field has a different number of sub-field (for example, some id has 4 members, but some have only 2 members) Is there any way that I could combine these data into something like a nested dictionary?每个 id 中包含 3 个字段,每个字段都有不同数量的子字段(例如,一些 id 有 4 个成员,但有些只有 2 个成员)有什么方法可以将这些数据组合成类似嵌套字典?

Here is the expected output:这是预期的 output:

{
 'id': 'Id_1', 
 'member': [{'Member_a': 2222}, {'Member_b': 3333}, {'Member_c': 4444}],
 'Device' : [{'Device_a': 5555}, {'Device_b': 6666}]
}

Thank you in advance!先感谢您!

In the code below, "blankpaper.txt" contains the text provided from you.在下面的代码中,“blankpaper.txt”包含您提供的文本。 I have constructed dictionaries that conform to the expected output and stored each one in the list dicts .我构建了符合预期的字典 output 并将每个字典存储在列表dicts中。

In my version, I have made all strings in the final output lower case though you can adjust the code accordingly based on your needs.在我的版本中,我已将最终 output 中的所有字符串设为小写,但您可以根据需要相应地调整代码。 I was not sure if your data file sometimes had for example, member_f , on one line, and Member_f on another line, or if that was just a typo above.我不确定您的数据文件是否有时在一行中有例如member_f ,而在另一行中有Member_f ,或者这是否只是上面的错字。 If similar information is known, the code can be made more efficient.如果知道类似的信息,则可以使代码更有效率。

dicts = []

with open("blankpaper.txt") as f:
    for line in f:
        # if line not empty
        if (split := line.split()):
            a = split[0].lower()
            b = a[0:a.rfind('_')]
            if "id" == b:
                temp = {'id': a, 'member': [], 'device': []}
                dicts.append(temp)
            elif "member" == b:
                temp['member'].append({a: int(split[1])})
            elif "device" == b:
                temp['device'].append({a: int(split[1])})

print(dicts)

Output Output

[{'id': 'id_1', 'member': [{'member_a': 2222}, {'member_b': 3333}, {'member_c': 4444}], 'device': [{'device_a': 5555}, {'device_b': 6666}]}, {'id': 'id_2', 'member': [{'member_a': 5678}, {'member_b': 1345}], 'device': [{'device_a': 3141}]}, {'id': 'id_3', 'member': [{'member_a': 5643}, {'member_b': 4678}, {'member_c': 4654}, {'member_e': 4674}, {'member_f': 2314}], 'device': [{'device_a': 4433}, {'device_b': 4354}]}]

I hope this helps.我希望这有帮助。 If there are any questions or if this is not exactly what you wanted, please let me know.如果有任何问题或者这不是您想要的,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM