将对象列表转换为字典

2024-09-28 03:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个城市对象列表,其中每个对象都有一个状态和一个名称。我想把这个列表转换成一个字典,其中州名是键,值是所有城市的列表。例如

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

现在我有

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

但它只是增加了每个州的最后一个城市,而不是所有的城市。最好的方法是什么?你知道吗


Tags: 对象namein名称列表for字典状态
2条回答

您可以这样做(使用更多python变量名:-):

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

你可以试试setdefault。你知道吗

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

相关问题 更多 >

    热门问题