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

jam*_*ieb 2 python

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

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

JRo*_*ite 9

您可以使用字典理解并尝试这样的事情:

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'}
Run Code Online (Sandbox Code Playgroud)

Python的2.6

b = dict((i['Key'], i['Value']) for i in a)
Run Code Online (Sandbox Code Playgroud)


Avi*_*Raj 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'}
Run Code Online (Sandbox Code Playgroud)

  • 好吧,我今天了解了dict理解. (2认同)