简体   繁体   中英

Take a dict from list

I take some lists from my database:

print(liste)
[('VEST', 'MODEL-1', 'BEIGE', 'M'), 
 ('VEST', 'MODEL-1', 'BEIGE', 'S'), 
 ('JACKET', 'MOD-1', 'GREEN', 'S'), 
 ('JACKET', 'MOD-1', 'GREEN', 'M'), 
 ('JACKET', 'MOD-2', 'BLACK', 'L'), 
 ('JACKET', 'MOD-2', 'BLACK', 'XL')]

now I need to create a dict like this:

mydict = {'VEST' : {'MODEL-1' : {'BEIGE' : ('S', 'M')}},
          'JACKET' : ({'MOD-1' : {'GREEN' : ('S', 'M')}},
                      {'MOD-2' : {'BLACK' : ('L', 'XL')}})}

I will use this in tkinter like json. I need to choose something like that:

print(mydict['JACKET'][1]['MOD-2']['BLACK'][0])
L
# Or
print(mydict['VEST']['MODEL-1']['BEIGE'][0])
S

How can I create a dict? I'm tired of trying different ways. I will be very happy if I can get good advice

What you are showing is not very consistent, but I think you may benefit from using a collections.defaultdict :

In [1]: from collections import defaultdict

In [2]: liste = [('VEST', 'MODEL-1', 'BEIGE', 'M'), 
   ...:  ('VEST', 'MODEL-1', 'BEIGE', 'S'), 
   ...:  ('JACKET', 'MOD-1', 'GREEN', 'S'), 
   ...:  ('JACKET', 'MOD-1', 'GREEN', 'M'), 
   ...:  ('JACKET', 'MOD-2', 'BLACK', 'L'), 
   ...:  ('JACKET', 'MOD-2', 'BLACK', 'XL')]

In [3]: mydict = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))

In [4]: for kind, model, color, size in liste:
   ...:     mydict[kind][model][color].append(size)
   ...:     

In [5]: mydict['VEST']['MODEL-1']['BEIGE']
Out[5]: ['M', 'S']

The defaultdict constructor takes a "factory" function as argument, ie a callable which is called without parameters to substitute a missing value. For example, defaultdict(list) will have an empty list for every missing key when you try to access it.

In this case I created a nested defaultdict object, which creates another defaultdict for every key. The inner one also creates a defaultdict , which also uses defaultdict as factory. This reflects your data hierarchy and saves you multiple checks or exception handling for missing keys.

You could try a defaultdict as demonstrated by @LevLevitsky, or you could try this workable, albeit convoluted way:

result = {}
for i in liste:
    if i[0] not in result.keys():
            result[i[0]] = {i[1]: {i[2]: tuple(i[3:4])}}
    else:
            if i[1] not in result[i[0]].keys():
                   result[i[0]][i[1]] = {i[2]: tuple(i[3:4])}
            else:
                   if i[2] not in result[i[0]][i[1]].keys():
                            result[i[0]][i[1]][i[2]] = tuple(i[3:4])
                   else:
                            result[i[0]][i[1]][i[2]]+=tuple(i[3:4])

print result #{'JACKET': {'MOD-2': {'BLACK': ('L', 'XL')}, 'MOD-1': {'GREEN': ('S', 'M')}}, 'VEST': {'MODEL-1': {'BEIGE': ('M', 'S')}}}

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