简体   繁体   English

将对象列表转换为字典

[英]Converting a list of objects to a dictionary

I have a list of city objects in which each object has a state and a name. 我有一个城市对象的列表,其中每个对象都有一个州和一个名称。 I want to convert this list to a dictionary where the state name is the key and the value is a list of all the cities. 我想将此列表转换为字典,其中州名是键,值是所有城市的列表。 For example, 例如,

"California" : [Ashland, Englewood, ...]

Right now I have 现在我有

newDictionary = dict((x.state, x.name) for x in objectList)

but it is only adding the last city of each state instead of all of them. 但是它只会添加每个州的最后一个城市,而不是所有州。 What is the best way to do this? 做这个的最好方式是什么?

You could do it like this (with more Pythonic variable names :-)): 您可以这样进行操作(使用更多Pythonic变量名称:-)):

state_with_cities = {}
for x in city_data_list:
    state_with_cities[x.state] = state_with_cities.get(x.state, []) + [x.name]

You can try setdefault . 您可以尝试setdefault

stateWithCities = {}
for x in cityDataList:
    stateWithCities.setdefault(x.state, []).append(x.name)

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

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