2011-03-07 53 views
0

在下面的代码中,Maps.objects.all()返回表中的所有对象并获取描述,将返回两个变量,即name,description。django python中的字典

现在我的问题是我正在构建一个dicetionary.If名称不在字典中,那么我应该添加它。如何做到这一点。

编辑 这需要上的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}) 

回答

0

完成从我明白,你想在字典中分配一个值的关键,如果它不存在。这是一个有用的网页dictionaries

现在,来解决你的问题,这应该做你想做的:

labels = {} 
maps = Maps.objects.all() 
for lm in maps: 
    name, description = getDescription(lm.name, lm.type) 
    if name not in labels: 
     labels[name] = description 
0

你应该使用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) 
0

一个更好的方法来做到这一点的单行:

labels = dict(Maps.objects.values_list('name', 'description'))