dictionary in django python
In the follwoing code Maps.objects.all() returns all the objects in the tables and get description will return two variables namely name,description.
Now my question i am constructing a dicetionary.If the nam开发者_开发问答e is not in the dictionary then i should add it.How this should be done.
EDIT This needs to be done on python2.4
labels = {}
maps Maps.objects.all()
for lm in maps:
(name,description) = getDescription(lm.name,lm.type)
if name not in labels:
labels.update({name,description})
From what I understand, you're trying to assign a value to a key in a dictionary if it doesn't exist. Here's a helpful page for dictionaries.
Now, to address your question, this should do what you want:
labels = {}
maps = Maps.objects.all()
for lm in maps:
name, description = getDescription(lm.name, lm.type)
if name not in labels:
labels[name] = description
you should use defaultdict
http://docs.python.org/library/collections.html
import collections
labels = collections.defaultdict(list)
maps = Maps.objects.all()
for lm in maps:
name, description = getDescription(lm.name, lm.type)
labels[name].append(description)
A much better way to do this in a single line:
labels = dict(Maps.objects.values_list('name', 'description'))
精彩评论