将字典列表变成单个字典
我一直在尝试将字典列表转换为单个字典,其中每个键是
,每个值是
。
简而言之,我有一个看起来像这样的列表。
[{'city': 'Normal',
'county': 'Madison County',
'state': 'Alabama'},
{'city': 'Birmingham',
'county': 'Jefferson County',
'state': 'Alabama'},
{'city': 'Montgomery',
'county': 'Montgomery County',
'state': 'Alabama'}]
我想将其更改为类似的内容,
{'Normal, Alabama': 'Madison County',
'Birmingham, Alabama': 'Jefferson County',
'Montgomery, Alabama': 'Montgomery County'}
我尝试了字典理解,但似乎无法同时添加两个不同的键。
所以我知道下面的代码将为我提供一本包含城市和县的键值对的字典
new_dict = {x['city']: x['county'] for x in counties}
但是,如何添加两个不同的键?像 new_dict = {x['city','state']: x['county'] for x in counties}
这样的东西是行不通的。
I've been trying to convert a list of dictionaries into a single dictionary in such a way where each key is <city>, <state>
and each value is <county>
.
In short I have a list that looks like this.
[{'city': 'Normal',
'county': 'Madison County',
'state': 'Alabama'},
{'city': 'Birmingham',
'county': 'Jefferson County',
'state': 'Alabama'},
{'city': 'Montgomery',
'county': 'Montgomery County',
'state': 'Alabama'}]
And I would like to change it into something like this
{'Normal, Alabama': 'Madison County',
'Birmingham, Alabama': 'Jefferson County',
'Montgomery, Alabama': 'Montgomery County'}
I tried dictionary comprehensions but can't seem to add two different keys at once.
So I know the code below will give me a dictionary with cities and counties for key value pairs
new_dict = {x['city']: x['county'] for x in counties}
However, how do I add two different keys? Something like new_dict = {x['city','state']: x['county'] for x in counties}
won't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用字典理解:
在这里,您使用 f 字符串组合两个键。
You can use dict comprehension:
Here, you combine two keys by using f-string.
您可以使用字符串连接来形成键:
这会输出:
You can use string concatenation to form the key:
This outputs:
为什么不只是一个简单的 for 循环呢?
Why not just a simple for loop?