!!这是一个直接可用的方法!!
看看效果!
- 我们有这样一个多层嵌套的多维字典:
# 老千层饼
data = {
'千层饼': {
'你以为我是第一层': {
'其实我是第五层': '呵呵',
'其实还有': {
'肉弹葱鸡': ['哦!'],
'又千层了': '重名了但是一样找到',
'字符串类型,但是我想转换成整数': '999'
}
},
'对': '对又怎么了',
'好得很': '嗯'
},
'呵呵': '怎么',
'又千层了': {
'是的': '确实',
'加一层': {
'再加一层': {
'嗯': '找到了'
}
}
}
}
- 如果我们想要从中拿一个数据出来,是十分麻烦的……
# 赋值
肉弹葱鸡 = data['千层饼']['你以为我是第一层']['其实还有']['肉弹葱鸡']
- 于是为了减少麻烦,我写了个可以直接使用的函数:
# 调用
肉弹葱鸡 = find('肉弹葱鸡', data)
print(肉弹葱鸡)
输出:['哦!']
- 很好!但是这个data字典里存在两个名字一样的键:
**又千层了**
,会不会有问题呢? - 不用担心!请看:
# 调用
多个结果 = findAll('又千层了',data)
print(多个结果)
输出:[{'是的': '确实', '加一层': {'再加一层': {'嗯': '找到了'}}}, '重名了但是一样找到']
- 嗯,函数直接找到了所有符合该键名的值。下面直接放出这两个方法:
# 查找单个键
def find(target, dictData, notFound='没找到'):
queue = [dictData]
while len(queue) > 0:
data = queue.pop()
for key, value in data.items():
if key == target: return value
elif type(value) == dict: queue.append(value)
return notFound
# 有多个同名键在字典里时,可以用这个方法
def findAll(target, dictData, notFound=[]):
queue = [dictData]
result = []
while len(queue) > 0:
data = queue.pop()
for key, value in data.items():
if key == target: result.append(value)
elif type(value) == dict: queue.append(value)
if not result: result = notFound
return result
完毕。
PurePeace
2020年3月24日