我有下面的代码片段,我想从字典列表中获取字典但是找不到全局名称项错误。想知道是否可以列举如下
l = [{1:{'item1':'value1'}},{2:{'item2':'value2'}}]
dic = dict(((k,v)) for k,v in item.items() for item in l)
print dic
答案 0 :(得分:1)
您对声明的排序是错误的。按照您在正常循环中订购它的方式来考虑它。因此,首先是for item in l
,然后是for k, v in item.items()
。
>>> dic = dict(((k,v)) for item in l for k,v in item.items())
>>> dic
{1: {'item1': 'value1'}, 2: {'item2': 'value2'}}
现在,理解成为
for item in l:
for k, v in item.items():
# Do Something
而不是
for k, v in item.items():
for item in l:
# Do Something
这是一个错误。
答案 1 :(得分:1)
您的for ... in ...
条款向后。它们的顺序应该与正常的for循环相同:
>>> l = [{1:{'item1':'value1'}},{2:{'item2':'value2'}}]
>>> dic = dict(((k,v)) for item in l for k,v in item.items())
>>> dic
{1: {'item1': 'value1'}, 2: {'item2': 'value2'}}
>>>
另外,我想指出在Python 2.6+中,您可以使用dict comprehension:
>>> l = [{1:{'item1':'value1'}},{2:{'item2':'value2'}}]
>>> dic = {k:v for item in l for k,v in item.items()}
>>> dic
{1: {'item1': 'value1'}, 2: {'item2': 'value2'}}
>>>
答案 2 :(得分:0)
列表理解被解释为正常的循环(实际上有点反直觉)所以你拥有的是
for k,v in item.items():
for item in mylist:
k,v
肯定你可以看到那个
的问题答案 3 :(得分:0)
首先提到问题How to create single Python dict from a list of dicts by summing values with common keys?
它将帮助您分析您的问题.....现在正常循环...
>>> dic = dict(((k,v)) for item in l for k,v in item.items())
>>> dic
{1: {'item1': 'value1'}, 2: {'item2': 'value2'}}
然后处理为....
for item in l:
for k, v in item.items():