将一堆键/值词典展平成一个字典?

时间:2015-11-25 04:46:39

标签: python

我想将此[{u'Key': 'color', u'Value': 'red'}, {u'Key': 'size', u'Value': 'large'}]转换为:{'color': 'red', 'size': 'large'}

有人有什么建议吗?我一直在玩列表推导,lambda函数和zip()超过一个小时,感觉我错过了一个明显的解决方案。谢谢!

3 个答案:

答案 0 :(得分:9)

您可以使用dictionary comprehension并尝试以下内容:

Python-2.7或Python-3.x

>>> a = [{u'Key': 'color', u'Value': 'red'}, {u'Key': 'size', u'Value': 'large'}]
>>> b = {i['Key']:i['Value'] for i in a}
>>> b
{'color': 'red', 'size': 'large'}

Python的2.6

b = dict((i['Key'], i['Value']) for i in a)

答案 1 :(得分:5)

使用dict理解。

>>> l = [{u'Key': 'color', u'Value': 'red'}, {u'Key': 'size', u'Value': 'large'}]
>>> {i['Key']:i['Value'] for i in l}
{'color': 'red', 'size': 'large'}

答案 2 :(得分:1)

使用Lambda函数。

a={}
dic = [{u'Key': 'color', u'Value': 'red'}, {u'Key': 'size', u'Value': 'large'}]
reduce(lambda x,y:a.__setitem__(y["Key"],y["Value"]),dic,a)

OP

print a
{'color': 'red', 'size': 'large'}

正如所建议:

import operator
reduce(lambda x,y:operator.setitem(a,y["Key"],y["Value"]),dic,a)
相关问题