简体   繁体   English

在 Python 中创建嵌套字典

[英]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).我创建了一个父亲“father_dict”字典,在其中存储列表类型数据,但我正在寻找该数据作为另一个字典的键存储(最终是一种嵌套字典)。

#            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.问题是当用{}' 替换 'father_dict [j] = [] 时,我得到一个属性错误,因为在字典中无法应用 append 方法,我尝试了一些类似匹配'father_dict [key] = data_input [ i ] [0] ' ,但它也不起作用。

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 .是的,您可以使用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.如果您提供“dict”作为默认值,那么您可以轻松设置键并按需创建子词典。

Here's your code using defaultdict:这是您使用 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.通过这种更改,您的father_dict 将包含本身就是字典的元素。 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.不幸的是,你不能有一个没有值的字典,因为你已经打印了它,所以你必须决定你想要的东西在上面的语句中是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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