2024-09-28 03:23:43 发布
网友
我有一个城市对象列表,其中每个对象都有一个状态和一个名称。我想把这个列表转换成一个字典,其中州名是键,值是所有城市的列表。例如
"California" : [Ashland, Englewood, ...]
现在我有
newDictionary = dict((x.state, x.name) for x in objectList)
但它只是增加了每个州的最后一个城市,而不是所有的城市。最好的方法是什么?你知道吗
您可以这样做(使用更多python变量名:-):
state_with_cities = {} for x in city_data_list: state_with_cities[x.state] = state_with_cities.get(x.state, []) + [x.name]
你可以试试setdefault。你知道吗
setdefault
stateWithCities = {} for x in cityDataList: stateWithCities.setdefault(x.state, []).append(x.name)
您可以这样做(使用更多python变量名:-):
你可以试试
setdefault
。你知道吗相关问题 更多 >
编程相关推荐