【问题标题】:Converting data into dictionary of Dictionaries in python在python中将数据转换为字典字典
【发布时间】:2014-04-04 19:01:24
【问题描述】:

我在 python 中使用键值对读取文件,例如

Mac:aaaa
IP:bbbbb
Name:dddd

Mac:wwwww
IP:fffff
Name:sssss

Mac:hhhh
IP:ddd
Name:fff

所以,我的查询是,我需要为上述数据构建一个字典字典,以便将其格式化为 json。

【问题讨论】:

  • 您需要至少添加一个您期望的 Python 结构示例;字典需要键,但你没有告诉我们这些键的来源,例如。

标签: python json dictionary


【解决方案1】:

我假设您的意思是字典列表,而不是字典字典

from operator  import methodcaller
fdata = open("data.txt").read().split()
split2 = methodcaller("split",":")
print map(dict, zip(*[iter(map(split2, fdata))]*3))

是一种有趣的方式;)

但是,如果您确实想要一本字典,正如您的标题所暗示的那样,您可以简单地

dict(enumerate(map(dict, zip(*[iter(map(split2, fdata.split()))]*3))))

[编辑为更符合 pep-8 :P]

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 2022-07-05
    • 2013-02-19
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    相关资源
    最近更新 更多