简体   繁体   English

将字典列表转换成字典

[英]Convert list of dictionaries into dict

I have the following list of one-element dictionaries: 我有以下一元字典列表:

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

How would I convert this into a dict? 我如何将其转换为字典? To get: 要得到:

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

You can do it with a dict comprehension : 您可以通过dict理解来做到这一点:

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

This syntax only works for Python versions >= 2.7 though. 不过,此语法仅适用于> = 2.7的Python版本。 If you are using Python < 2.7, you'd have to do something like: 如果使用的是Python <2.7,则必须执行以下操作:

dict([(k,v) for element in dictList for k,v in element.items()])

If you're unfamiliar with such nesting inside a comprehension, what I've done is equivalent to: 如果您不了解这种理解内的嵌套,那么我所做的等同于:

newDict = {}
for element in dictList:
    for k,v in element.items():
        newDict[k] = v

I'd probably just do: 我可能会做:

dct = {}
for sub_dict in lst:
    dct.update(sub_dict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM