将字典列表转换成字典 [英] Convert list of dictionaries into dict

查看:164
本文介绍了将字典列表转换成字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一元字典列表:

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'
}


推荐答案

您可以使用 dict理解

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

此语法仅适用于> = 2.7的Python版本。如果您使用的是Python< 2.7,您必须执行以下操作:

This syntax only works for Python versions >= 2.7 though. If you are using Python < 2.7, you'd have to do something like:

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

这篇关于将字典列表转换成字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆