我必须递归查找其值不包含其他字典的字典,然后基于该字典创建一个新字典,当前,我的递归函数能够处理字典词典
b= {'order': {'id': u'62211'}, 'no': 0, 'data': 340, 'instruction': {'id': u'99AA', 'version': u'1', 'validation': ('nota', None), 'time': 9001, 'instructions': [], 'restart': True}}
temp_1={}
import copy
def getKeys(d):
for k,v in d.items():
if isinstance(v, dict):
getKeys(v)
else:
temp_1[k]=v
return temp_1
a= getKeys(b)
Output
{'no': 0, 'version': u'1', 'time': 9001, 'validation': ('nota', None), 'data': 340, 'id': u'62211', 'restart': True, 'instructions': []}
但是在某些情况下,字典会出现在列表或元组中时,请不确定如何以递归方式处理它。
ab={'apple':9,'ball':{'cat':8,'www':('data',{'new':'hello','ppp':('dat',[{'jjj':'world'}])})}}
expected output:
{ 'apple':9,'cat':8,'new':'hello','jjj':'world'}
答案 0 :(得分:1)
def get_keys(x, tmp=None):
if tmp is None: tmp = {}
if isinstance(x, dict):
for key,value in x.items():
if isinstance(value, dict):
get_keys(value, tmp)
elif isinstance(value, (tuple, list, set):
for item in value:
get_keys(item, tmp)
else:
tmp[key] = value
elif isinstance(x, (tuple, list set)):
for item in x:
get_keys(item, tmp)
return tmp
b= {'order': {'id': u'62211'}, 'no': 0, 'data': 340, 'instruction': {'id': u'99AA', 'version': u'1', 'validation': ('nota', None), 'time': 9001, 'instructions': [], 'restart': True}}
ab={'apple':9,'ball':{'cat':8,'www':('data',{'new':'hello','ppp':('dat',[{'jjj':'world'}])})}}
a = get_keys(ab)
aa = get_keys(b)
print(a)
print(aa)
答案 1 :(得分:1)
您只需要处理iterable
个项目(而不仅仅是dict
)。这里是一个例子:
import collections
example_data = {
'apple': 9,
'ball': {
'cat': 8,
'www': (
'data',
{
'new': 'hello',
'ppp': (
'dat',
[{'jjj': 'world'}]
)
}
)
}
}
def get_keys(data, result=None):
result = result or dict()
# dict processing
if isinstance(data, dict):
for key, value in data.items():
# not str, but iterable - call get_keys one more time
if type(value) != str and isinstance(value, collections.Iterable):
result = get_keys(value, result)
else:
# value isn't iterable - just set to result
result[key] = value
# list, tuple, set processing
elif isinstance(data, (list, tuple, set)):
for item in data:
# list item is not str, but iterable - call get_keys one more time
if type(item) != str and isinstance(item, collections.Iterable):
result = get_keys(item, result)
return result
print(get_keys(example_data))
希望这会有所帮助。
答案 2 :(得分:0)
您可以使用一个函数来处理dict
,并使用另一个函数来处理tuple
和list
。根据元素的类型,您可以选择要应用的功能:
result = {}
def process_list(l):
for x in l:
try:
process[type(x)](x)
except KeyError:
pass
def process_dict(d):
for k, v in d.items():
try:
process[type(v)](v)
except KeyError:
result[k] = v
process = {
list: process_list,
tuple: process_list,
dict: process_dict
}
然后仅致电process_dict(ab)
。