class DictionaryProcessingSet:
result_dict = {}
def get_key(self, data: dict, demand: list, countKey: str = ''):
"""
:param data: 入参数据
:param demand: 你的需求参数
:param countKey: 参数统计次数
:return:
"""
if isinstance(data, dict): # 判断入参数据是否是dict类型
for demand_i in demand: # 根据你的需求参数遍历
if demand_i in str(data): # 判断需求参数是否存在与入参数据中
for key in data.keys(): # 根据入参数据key进行遍历
if demand_i == key: # 如果入参数据得key=需求参数那就输出
self.result_dict[key] = data[key]
break
elif isinstance(data[key], dict): # 如果最外层key找不到,那就根据value是否是dict进入内层寻找
self.zero_time_variable = [] # 储存当前需求参数
if demand_i in str(data[key]): # 根据需求参数判断是否存在于value得dict中
self.zero_time_variable.append(demand_i)
self.get_key(data[key], self.zero_time_variable,countKey) # 拿到内层得dict进行新一轮得循环
elif isinstance(data[key], (tuple, list)): # 判断当前key值是否是dict或者tuple
for data_i in data[key]: # 循环list
if demand_i in str(data_i) and isinstance(data_i, dict): # 判断需求参数是否存在且内部类型是dict
self.get_key(data_i, self.zero_time_variable,countKey) # 拿到内层得dict进行新一轮得循环
else:
self.result_dict[demand_i] = '未查询到该key' # 需求参数不在入参数据中
countName = countKey + "共计"
self.result_dict[countName] = str(data).count(countKey) # 统计某个参数在当前入参数据中出现得次数
return self.result_dict
dictData = {
"name": "John",
"age": 30,
"wife": {
"firstWife": "王丽",
"secondWife": "李银",
},
"child": {
"boy": '赵明',
"girl": '赵琴',
"wife": '小三',
"sunDynasty": {
"sunBoy": '赵鹏鹏',
"sunGirl": '赵茵茵',
"greatGrandson": [
{"greatSunBoy": '赵阳'},
{"greatSunGirl": '赵雨'},
]
}
}
}
"""如何知道某一个值是否存在变量中"""
seek = DictionaryProcessingSet().get_key(dictData, ['greatSunGirl', 'girl', 'age', 'firstWife', 'wife', '我不在哦', 'sunGirl'], 'wife')
print(seek)
"""
结果:{'greatSunGirl': '赵雨', 'wife共计': 2, 'girl': '赵琴', 'age': 30, 'firstWife': '王丽', 'wife': {'firstWife': '王丽', 'secondWife': '李银'}, '我不在哦': '未查询到该key', 'sunGirl': '赵茵茵'}
"""
标签:python,self,嵌套,dict,key,demand,参数,data,字典
From: https://www.cnblogs.com/wyj497022944/p/17752261.html