【问题标题】:python: dynamic keys in nested dictionarypython:嵌套字典中的动态键
【发布时间】:2022-01-15 02:29:58
【问题描述】:

我正在使用 django shell 来尝试创建这样的字典:

{'TITLE SECTION ONE': 
  {'Category One': [element one],
  'Category Two': [element one,
                  <element two},
 'TITLE SECTION TWO': 
  {'Category One': [element one,
                   element two}

但是这段代码:dict[section][category] ​​= [x] 将“二”中的“价格元素一”更改为如下结果。

dict = dict()
for x in price.objects.all():
   if section not in dict:
       dict[section] = {
       category: [x]
   }
   else:
        dict[section][category] = [x]
        dict[section][category].append(x)




    {'TITLE SECTION ONE': 
      {'Category One': [element two],
      'Category Two': [element two,
                      element two},
     'TITLE SECTION TWO': 
      {'Category One': [element two,
                       element two}}

如何保留所有元素?

【问题讨论】:

  • 无论类别是否存在,您都创建一个新列表并在其中添加两次x。
  • @WillemVanOnsem 我不必使用 dict[section][category] ​​= [x] 吗?

标签: python django


【解决方案1】:

如果类别尚未在mydict[section 中定义,您应该只构建一个新列表,因此:

mydict = {}
for x in price.objects.all():
    if section not in mydict:
         mydict[section] = { category: [x] }
    elif category not in mydict[section]:
         mydict[section][category] = [x]
    else:
         mydict[section][category].append(x)

另一种选择是使用defaultdict:

from collections import defaultdict

mydict = defaultdict(lambda: defaultdict(list))
for x in price.objects.all():
    mydict[section][category].append(x)

mydict = {k: dict(v) for k, v in mydict.items()}

注意:请不要将变量命名为dict,它会覆盖对dict builtin function [Python-doc] 的引用。例如使用mydict。

【讨论】:

  • 谢谢,我尝试了类似的解决方案,但我在 elif 中弄错了密钥。再次感谢
猜你喜欢
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-30
  • 2018-06-02
  • 2021-06-21
  • 2021-05-10
  • 1970-01-01
相关资源
最近更新 更多