简体   繁体   中英

Create a nested dictionary in Python

I have created a Father 'father_dict' dictionary, in which I store list type data, but I am looking for that data to be stored as the key of another dictionary, (ultimately a kind of nested dictionary).

#            SubKey            Key
data_input = [[ 1,     'Col',   1,    'TWO',    450],  
              [ 2,     'Col',   1,    'TWO',    450],   
              [ 3,     'Col',   1,    'TWO',    450],   
              [ 4,     'Col',   2,    'TWO',    400],
              [ 5,     'Col',   2,    'TWO',    400],  
              [ 6,     'Col',   2,    'TWO',    400],   
              [ 7,     'Col',   3,    'TWO',    300],
              [ 8,     'Col',   3,    'TWO',    300],
              [ 9,     'Col',   3,    'TWO',    300]] 
cc_list = []
father_dict = {}

for i in range(len(data_input)): 
    if data_input[i][1] == 'Col':
        cc_list.append(data_input[i][2]) #--> key list
flat_list = list(set(cc_list)) #--> Key flat

for j in flat_list:
    father_dict[j] = []

for i in range(len(data_input)):
    if data_input[i][1] == 'Col':
        key = data_input[i][2]
        father_dict[key].append(data_input[i][0])
print('\n', 'Father Dict ')
print(father_dict)      

The problem is that when replacing 'father_dict [j] = [] with {}' , I get an Attribute error because in dictionaries the append method cannot be applied, I have tried some things like matching 'father_dict [key] = data_input [ i] [0] ' , but it doesn't work either.

What I'm looking for is that when printing on screen it returns this:

 Father Dict 
{1: {1:, 2:, 3:}, 2: {4:, 5:, 6:}, 3: {7:, 8:, 9:}}

Is there any method that works for these cases, thanks?

Yes, you can use a defaultdict . It's like a dictionary, except you can provide a default value for any key that doesn't exist. If you provide "dict" as the default value, then you can easily set keys and the subdictionaries get created on demand.

Here's your code using defaultdict:

from collections import defaultdict
import json

#            SubKey            Key
data_input = [[ 1,     'Col',   1,    'TWO',    450],  
              [ 2,     'Col',   1,    'TWO',    450],   
              [ 3,     'Col',   1,    'TWO',    450],   
              [ 4,     'Col',   2,    'TWO',    400],
              [ 5,     'Col',   2,    'TWO',    400],  
              [ 6,     'Col',   2,    'TWO',    400],   
              [ 7,     'Col',   3,    'TWO',    300],
              [ 8,     'Col',   3,    'TWO',    300],
              [ 9,     'Col',   3,    'TWO',    300]] 
cc_list = []
father_dict = defaultdict(dict)

for i in range(len(data_input)): 
    if data_input[i][1] == 'Col':
        cc_list.append(data_input[i][2]) #--> key list
flat_list = list(set(cc_list)) #--> Key flat

for i in range(len(data_input)):
    if data_input[i][1] == 'Col':
        key = data_input[i][2]
        father_dict[key][data_input[i][0]] = None
print('\n', 'Father Dict ')
print(json.dumps(father_dict).replace(" null", "").replace('"', ''))  

Printing out the result wasn't as convenient, and there's probably a better way which I was too lazy to find, but hopefully you get the idea.

With that change, your father_dict will contain elements which are themselves dictionaries. This means that

father_dict[key]

returns a dictionary, not a list. So, if you want to set something in this dictionary, use

father_dict[key][j] = something

Unfortunately, you can't have a dictionary without a value, as you've printed it, so you have to decide what you want the something to be in the above statement.

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