Declaring a multi dimensional dictionary in python

后端 未结 8 1623
闹比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:37

    Do you mean dict or list?

    And if you mean dict do you want the second level to be another dict? or a list?

    For a dict to work you need to have declared the keys ahead of time.

    So if it's dicts in dicts you need something like this:

    new_dic = {}
    try:
        new_dic[1][2] = 5
    except KeyError:
        new_dic[1] = {2:5}
    

提交回复
热议问题