python - 将一堆键/值字典拼合成一个字典?

标签 python

我想转换这个:[{u'Key': 'color', u'Value': 'red'}, {u'Key': 'size', u'Value': 'large '}] 到此:{'color': 'red', 'size': 'large'}

有人有什么建议吗?一个多小时以来,我一直在研究列表理解、lambda 函数和 zip(),我觉得我缺少一个明显的解决方案。谢谢!

最佳答案

您可以使用 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)

关于python - 将一堆键/值字典拼合成一个字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33908636/

相关文章:

python - 获取列表中的所有非唯一元素

python - 虚拟环境指定使用的Python实例

Python IDLE 无法启动 (Mac) - 来自 Python/Unix 新手的问题

python - 在python中的文件中写入多行

python - 循环中从数据帧获取最大值和最小值

python - 从 numpy 数组中删除条目

python - 如何从 tkinter 中的 excel 值中下拉?

python - Suds 忽略代理设置

python - 当使用 f.read() 每个字母的迭代循环

Python:LXML - 如何将元素添加到现有元素树