我有一个城市对象列表,其中每个对象都有一个州和一个名字。我想将此列表转换为字典,其中州名称是键,值是所有城市的列表。例如,
"California" : [Ashland, Englewood, ...]
现在我有
newDictionary = dict((x.state, x.name) for x in objectList)
但它只是添加了每个州的最后一个城市而不是所有州。这样做的最佳方式是什么?
答案 0 :(得分:4)
您可以尝试from django.db import models
from django.contrib.contenttypes.fields import GenericRelation
class Bookmark(models.Model):
url = models.URLField()
tags = GenericRelation(TaggedItem)
。
setdefault
答案 1 :(得分:3)
你可以这样做(有更多的Pythonic变量名: - )):
state_with_cities = {}
for x in city_data_list:
state_with_cities[x.state] = state_with_cities.get(x.state, []) + [x.name]