简体   繁体   中英

python: dynamic keys in nested dictionary

i am using the django shell to try to create such a dictionary:

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

but this pieces of code: dict[section][category] = [x] change the "price element one" in "two" like the result below.

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)




    {'SECTION ONE': 
      {'Category One': [<Price: price element two>],
      'Category Two': [<Price: price element two>,
                      <Price: price element two>]},
     'SECTION TWO': 
      {'Category One': [<Price: price element two>,
                       <Price: price element two>]}}

how can you keep all the elements?

You should only construct a new list if the category is not yet defined in the mydict[section , so:

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)

another option is to work with a 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()}

Note : Please do not name a variable dict , it overrides the reference to the dict builtin function [Python-doc] . Use for example mydict .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM