字典 (dictionary)
Python 中的dict可以实现迅速查找。那么有没有像数组有二维数组一样,有二维的字典呢?比如我需要对两个关键词进行查找的时候。2D dict 可以通过
dict_2d = {‘a’: {‘a’: 1, ‘b’: 3}, ‘b’: {‘a’: 6}}
1
来建立,并通过
dict_2d[‘a’][‘b’]
1
来访问。但是添加一个新的 “key-value”对却比较复杂。对一维字典,可以用
dict_1d = dict()
dict_1d[‘a’] = 1
1
2
或者
dict_1d.update({‘a’: 1})
1
来实现。但是”2-D” dictionary 新添一个”key-value”对时,不能简单的用
dict_2d[‘a’][‘c’] = 8
1
的形式。因为二维字典的两层key和value之间会混淆,需要判断第一个key是否已经存在了。添加二维的字典可以通过一个函数来简单实现:
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}})
1
2
3
4
5
比如可以用作查找城市之间的距离
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’]
1
2
3
4
5
6
7
8
9
10
还是挺方便的。
同理,三维数组
def addtodict3(thedict,key_a,key_b,key_c,val):
if key_a in thedict:
if key_b in thedict[key_a]:
thedict[key_a][key_b].update({key_c:val})
else:
thedict[key_a].update({key_b:{key_c:val}})
else:
thedict.update({key_a:{key_b:{key_c:val}}})
遍历三维字典
for key1 in thedict:
for key2 in thedict[key1]:
for key3 in thedict[key1][key2]:
print thedict[key1][key2][key3]