[英]Pythonic way to transform list of pairs to dict
I have a List of pairs like this: 我有这样一个配对列表:
[
{'Name': 'first_name', 'Value': 'Joe'},
{'Name': 'last_name', 'Value': 'Smith'},
{'Name': 'gender', 'Value': 'male'}
]
I want to transform it into a Dict like this: 我想将其转换成这样的Dict:
{
'first_name': 'Joe',
'last_name': 'Smith',
'gender': 'male'
}
I am currently using a simple loop to accomplish this now but I know there is a more Pythonic way to do it. 我目前正在使用一个简单的循环来完成此操作,但我知道还有一种更Python化的方法可以执行此操作。 Thoughts?
有什么想法吗?
-Tony -托尼
It was easier than I expected: 这比我预期的容易:
{pair['Name']:pair['Value'] for pair in source_list}
This uses a feature of Python called a Dict comprehension. 这使用了称为Dict理解的Python功能。
您可以在列表中的每个字典上使用values()
方法的生成器输出实例化字典:
dict(d.values() for d in l)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.