python - 将字典列表转换为字典

标签 python dictionary

我有以下单元素词典列表:

[{'\xe7': '\xe7\x95\xb6\xe6\x96\xb0\x.'}, {'...\xe6\x991\xe7\xa8\x': 'asdf'}]

我将如何将其转换为字典?要得到:
{
    '\xe7': '\xe7\x95\xb6\xe6\x96\xb0\x.',
    '...\xe6\x991\xe7\xa8\x': 'asdf'
}

最佳答案

你可以用字典理解来做到这一点:

{k:v for element in dictList for k,v in element.items()}

但是,此语法仅适用于 >= 2.7 的 Python 版本。如果您使用的是 Python < 2.7,则必须执行以下操作:
dict([(k,v) for element in dictList for k,v in element.items()])

如果你不熟悉在理解中的这种嵌套,我所做的相当于:
newDict = {}
for element in dictList:
    for k,v in element.items():
        newDict[k] = v

关于python - 将字典列表转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28243504/

相关文章:

Python - 嵌套字典,与散列元组?

javascript - `.map` 不是用于循环吗?

python 3 : Conditional extraction of keys from a dictionary with comprehension

python - django(但实际上是 python)关于元组的古玩

python - 如何使用 WTForms 将 HTML 表单中的可变长度字符串列表发送到 Flask?

python - 获取 Python 中 if 语句中满足哪个或条件

python - 如何比较或测量Tensorflow中模型的实际大小?

python - 消息读取脚本显示机器人自己的消息并永远循环

C#:Dictionary 的 [string] 索引器返回什么?

python - 将列表中的值附加到字典中