Python's two-dimension dictionary definition and implementation method, twodimensioncode
This article describes how to define and implement the "two-dimension dictionary" dictionary in Python. We will share this with you for your reference. The details are as follows:
Dict in Python allows quick search. Is there a two-dimensional dictionary like an array with two-dimensional arrays? For example, when I need to search for two keywords. 2D dict
dict_2d = {'a': {'a': 1, 'b': 3}, 'b': {'a': 6}}
And
dict_2d['a']['b']
. However, adding a new "key-value" pair is complicated. For one-dimensional dictionaries, you can use
dict_1d = dict()dict_1d['a'] = 1
Or
dict_1d.update({'a': 1})
. However, when "2-D" dictionary adds a new "key-value" pair
dict_2d['a']['c'] = 8
. Because the two-layer keys and values of the two-dimensional dictionary are confused, you need to determine whether the first key already exists. You can use a function to add a two-dimensional dictionary:
def addtwodimdict(thedict, key_a, key_b, val): if key_a in adic: thedict[key_a].update({key_b: val}) else: thedict.update({key_a:{key_b: val}})
For example, it can be used to find the distance between cities.
mapdict = dict()addtwodimdict(mapdict, 'Beijing', 'Guangzhou', 1897)addtwodimdict(mapdict, 'Chengdu', 'Guangzhou', 1243)addtwodimdict(mapdict, 'Guangzhou', 'Shanghai', 1212)addtwodimdict(mapdict, 'Beijing', 'Chengdu', 1516)addtwodimdict(mapdict, 'Chengdu', 'Shanghai', 1657)addtwodimdict(mapdict, 'Beijing', 'Shanghai', 1075)print 'The distance between Chengdu and Guangzhou is ',mapdict['Chengdu']['Guangzhou']
It is quite convenient.