在Python中我有一個dict
如下:將嵌套字典轉換爲python列表?
{'name':{0:'tom',1:'dav'}, 'age':{0:22,1:23}}
我希望它改成這樣:
[{'name':'tom','age':22}, {'name':'dav','age':23}]
你能和這樣做的最簡單的方式回答?
在Python中我有一個dict
如下:將嵌套字典轉換爲python列表?
{'name':{0:'tom',1:'dav'}, 'age':{0:22,1:23}}
我希望它改成這樣:
[{'name':'tom','age':22}, {'name':'dav','age':23}]
你能和這樣做的最簡單的方式回答?
這樣的事情呢?
>>> d = {'name':{0:'tom',1:'dav'}, 'age':{0:22,1:23}}
>>> values = zip(*[value.values() for value in d.values()])
>>> l = [{'name': name, 'age': age} for name, age in values]
>>> l
[{'name': 'tom', 'age': 22}, {'name': 'dav', 'age': 23}]
[value.values() for value in d.values()]
回報[['tom', 'dav'], [22, 23]]
這是你的subdicts的值,然後,zip()
回報[('tom', 22), ('dav', 23)]
。
然後,我們使用for
循環遍歷壓縮值,並將值放入l
的字符串中。
在一行另一變型:
a = {'name':{0:'tom',1:'dav'}, 'age':{0:22,1:23}}
[ dict(zip(*(a.keys(),y))) for y in zip(*(x.values() for x in a.values())) ]
,另一個在一行中)
age,name = {'name':{0:'tom',1:'dav'}, 'age':{0:22,1:23}}.values()
print [{'name': name[inx],'age':age[inx]} for inx in age]
[{'age': 22, 'name': 'tom'}, {'age': 23, 'name': 'dav'}]