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 KeyError
:
new_dic[1][2] = 5 KeyError: 1
How to do this?
Method #1 : Using setdefault() This function is used to define an empty dictionary on 1st nested level of dictionary to make it 2D. In this case there is no need to define explicit dictionaries at that level of dictionary.
Creating a Nested Dictionary In Python, a Nested dictionary can be created by placing the comma-separated dictionaries enclosed within braces.
A Dictionary in python is declared by enclosing a comma-separated list of key-value pairs using curly braces({}). Python Dictionary is classified into two elements: Keys and Values. Values can be a list or list within a list, numbers, etc.
In Python, Multidimensional Array can be implemented by fitting in a list function inside another list function, which is basically a nesting operation for the list function. Here, a list can have a number of values of any data type that are segregated by a delimiter like a comma.
A multi-dimensional dictionary is simply a dictionary where the values are themselves also dictionaries, creating a nested structure:
new_dic = {} new_dic[1] = {} new_dic[1][2] = 5
You'd have to detect that you already created new_dic[1]
each time, though, to not accidentally wipe that nested object for additional keys under new_dic[1]
.
You can simplify creating nested dictionaries using various techniques; using dict.setdefault()
for example:
new_dic.setdefault(1, {})[2] = 5
dict.setdefault()
will only set a key to a default value if the key is still missing, saving you from having to test this each time.
Simpler still is using the collections.defaultdict()
type to create nested dictionaries automatically:
from collections import defaultdict new_dic = defaultdict(dict) new_dic[1][2] = 5
defaultdict
is just a subclass of the standard dict
type here; every time you try and access a key that doesn't yet exist in the mapping, a factory function is called to create a new value. Here that's the dict()
callable, which produces an empty dictionary when called.
Demo:
>>> new_dic_plain = {} >>> new_dic_plain[1] = {} >>> new_dic_plain[1][2] = 5 >>> new_dic_plain {1: {2: 5}} >>> new_dic_setdefault = {} >>> new_dic_setdefault.setdefault(1, {})[2] = 5 >>> new_dic_setdefault {1: {2: 5}} >>> from collections import defaultdict >>> new_dic_defaultdict = defaultdict(dict) >>> new_dic_defaultdict[1][2] = 5 >>> new_dic_defaultdict defaultdict(<type 'dict'>, {1: {2: 5}})
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With