【问题标题】:dictionary in django pythondjango python中的字典
【发布时间】:2011-03-07 10:38:22
【问题描述】:

在下面的代码中 Maps.objects.all() 返回表中的所有对象,get description 将返回两个变量,即 name,description。

现在我的问题是我正在构建一个字典。如果该名称不在字典中,那么我应该添加它。应该如何完成。

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

【问题讨论】:

    标签: django django-views python


    【解决方案1】:

    据我了解,如果字典中的键不存在,您会尝试为其分配一个值。这是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
    

    【讨论】:

      【解决方案2】:

      你应该使用默认字典

      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)
      

      【讨论】:

        【解决方案3】:

        在一行中执行此操作的更好方法:

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

        【讨论】:

          猜你喜欢
          • 2011-10-24
          • 2018-10-22
          • 1970-01-01
          • 2012-05-09
          • 2012-01-22
          • 1970-01-01
          • 1970-01-01
          • 2018-08-06
          • 2020-01-02
          相关资源
          最近更新 更多