Declaring a multi dimensional dictionary in python

后端 未结 8 1586
闹比i
闹比i 2020-12-08 02:03

I need to make a two dimensional dictionary in python. e.g. new_dic[1][2] = 5

When I make new_dic = {}, and try to insert values, I get a <

相关标签:
8条回答
  • 2020-12-08 02:51

    u can try this, it is even easier if it is string

    new_dic = {}
    a = 1
    new_dic[a] = {}
    b = 2
    new_dic[a][b] = {}
    c = 5
    new_dic[a][b]={c}
    

    type

    new_dic[a][b]
    >>>'5'
    

    For string

    new_dic = {}
    a = "cat"
    new_dic[a] = {}
    b = "dog"
    new_dic[a][b] = {}
    c = 5
    new_dic[a][b] = {c}
    

    type

    new_dic["cat"]["dog"]
    >>>'5'
    
    0 讨论(0)
  • 2020-12-08 02:52

    Check it out:

    def nested_dict(n, type):
        if n == 1:
            return defaultdict(type)
        else:
            return defaultdict(lambda: nested_dict(n-1, type))
    

    And then:

    new_dict = nested_dict(2, float)
    

    Now you can:

    new_dict['key1']['key2'] += 5
    

    You can create as many dimensions as you want, having the target type of your choice:

    new_dict = nested_dict(3, list)
    new_dict['a']['b']['c'].append(5)
    

    Result will be:

    new_dict['a']['b']['c'] = [5]
    
    0 讨论(0)
提交回复
热议问题