gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:51:24 25 4
gpt4 key购买 nike

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

[{'\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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com