如何将txt文件中的行分组到嵌套字典中(Python)
我有一个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
每个id包含3个字段,每个字段都有不同数量的子字段(例如,有些id有4个成员,但有些只有2个成员)是否有有什么方法可以将这些数据组合成嵌套字典之类的东西吗?
这是预期的输出:
{
'id': 'Id_1',
'member': [{'Member_a': 2222}, {'Member_b': 3333}, {'Member_c': 4444}],
'Device' : [{'Device_a': 5555}, {'Device_b': 6666}]
}
提前谢谢您!
I have a txt file that contain the data as below:
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?
Here is the expected 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在下面的代码中,“ blankpaper.txt”包含您提供的文本。我构建了符合预期输出的字典,并将每个输出存储在列表
dicts
中。在我的版本中,我已经在最终输出较低的情况下制作了所有字符串,尽管您可以根据自己的需求相应地调整代码。我不确定您的数据文件有时是否有例如
成员_F
在一行中,而成员_F
在另一行上,或者这只是上面的错别字。如果已知类似的信息,则可以使代码更有效。输出
我希望这会有所帮助。如果有任何疑问,或者这不是您想要的,请告诉我。
In the code below, "blankpaper.txt" contains the text provided from you. I have constructed dictionaries that conform to the expected output and stored each one in the list
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. I was not sure if your data file sometimes had for example,
member_f
, on one line, andMember_f
on another line, or if that was just a typo above. If similar information is known, the code can be made more efficient.Output
I hope this helps. If there are any questions or if this is not exactly what you wanted, please let me know.