简体   繁体   中英

Converting data into dictionary of Dictionaries in python

I am reading a file in python using a key value pair, for example

Mac:aaaa
IP:bbbbb
Name:dddd

Mac:wwwww
IP:fffff
Name:sssss

Mac:hhhh
IP:ddd
Name:fff

so, my query is, I need to build a dictionary of dictionaries for the above data so as to format it as json.

I assume you mean a list of dictionaries, not a dictionary of dictionaries

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

is a fun way to do it ;)

however if you did want a dictionary of dictionaries as your title suggests you can simply

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

[edited to be more pep-8 compliant :P ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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