是否有一种简单的迭代嵌套字典的方法,嵌套字典可能包含其他对象,如列表,元组,然后是字典,以便迭代涵盖这些其他对象的所有元素?
例如,如果我键入嵌套字典对象的键,我会将它全部列在Python解释器中。
[edit] 这里是示例词典:
{
'key_1': 'value_1',
'key_2': {'key_21': [(2100, 2101), (2110, 2111)],
'key_22': ['l1', 'l2'],
'key_23': {'key_231': 'v'},
'key_24': {'key_241': 502,
'key_242': [(5, 0), (7, 0)],
'key_243': {'key_2431': [0, 0],
'key_2432': 504,
'key_2433': [(11451, 0), (11452, 0)]
},
'key_244': {'key_2441': {'key_24411': {'key_244111': 'v_24411',
'key_244112': [(5549, 0)]
},
'key_24412':'v_24412'
},
'key_2441': ['ll1', 'll2']
}
},
}
}
抱歉不可读,但我尽我所能。
答案 0 :(得分:18)
def recurse(d):
if type(d)==type({}):
for k in d:
recurse(d[k])
else:
print d
答案 1 :(得分:4)
上面Graddy的recurse()
答案的生成器版本不应该在字符串上爆炸,还会给你复合键(cookie crumb trail?),显示你是如何达到某个值的:
def recurse(d, keys=()):
if type(d) == dict:
for k in d:
for rv in recurse(d[k], keys + (k, )):
yield rv
else:
yield (keys, d)
for compound_key, val in recurse(eg_dict):
print '{}: {}'.format(compound_key, val)
生成输出(使用问题中提供的示例字典):
('key_1',): value_1
('key_2', 'key_21'): [(2100, 2101), (2110, 2111)]
('key_2', 'key_22'): ['l1', 'l2']
('key_2', 'key_23', 'key_231'): v
('key_2', 'key_24', 'key_241'): 502
('key_2', 'key_24', 'key_243', 'key_2433'): [(11451, 0), (11452, 0)]
('key_2', 'key_24', 'key_243', 'key_2432'): 504
('key_2', 'key_24', 'key_243', 'key_2431'): [0, 0]
('key_2', 'key_24', 'key_242'): [(5, 0), (7, 0)]
('key_2', 'key_24', 'key_244', 'key_2441'): ['ll1', 'll2']
在Python 3中,第二个yield循环应该可以用yield from
替换。通过使用来自集合模块的映射ABC将type(d) == dict
测试替换为isinstance(d, collections.Mapping)
,可以使此生成器更加通用。
答案 2 :(得分:2)
迭代包含意外嵌套元素的嵌套字典。
这是我的解决方案:
# d is the nested dictionary
for item in d:
if type(item) == list:
print "Item is a list"
for i in item: print i
elif type(item) == dict:
print "Item is a dict"
for i in item: print i
elif type(item) == tuple:
print "Item is a tuple"
for i in item: print i
else:
print "Item is not a list, neither a dict and not even a tuple"
print item
我认为上面的例子非常通用,你可以根据你的用例来塑造它。
答案 3 :(得分:2)
这是另一种解决方案,
#!/usr/bin/python
d = {'key_1': 'value_1',
'key_2': {'key_21': [(2100, 2101), (2110, 2111)],
'key_22': ['l1', 'l2'],
'key_23': {'key_231': 'v'},
'key_24': {'key_241': 502,
'key_242': [(5, 0), (7, 0)],
'key_243': {'key_2431': [0, 0],
'key_2432': 504,
'key_2433': [(11451, 0), (11452, 0)]},
'key_244': {'key_2441': ['ll1', 'll2']}}}}
def search_it(nested, target):
found = []
for key, value in nested.iteritems():
if key == target:
found.append(value)
elif isinstance(value, dict):
found.extend(search_it(value, target))
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
found.extend(search_it(item, target))
else:
if key == target:
found.append(value)
return found
keys = [ 'key_242', 'key_243', 'key_242', 'key_244', 'key_1' ]
for key in keys:
f = search_it(d, key)
print 'Key: %s, value: %s' % (key, f[0])
输出:
Key: key_242, value: [(5, 0), (7, 0)]
Key: key_243, value: {'key_2433': [(11451, 0), (11452, 0)], 'key_2432': 504, 'key_2431':
[0, 0]}
Key: key_242, value: [(5, 0), (7, 0)]
Key: key_244, value: {'key_2441': ['ll1', 'll2']}
Key: key_1, value: value_1
答案 4 :(得分:0)
如何使用通用包装器生成器,如下所示:
def recursive(coll):
"""Return a generator for all atomic values in coll and its subcollections.
An atomic value is one that's not iterable as determined by iter."""
try:
k = iter(coll)
for x in k:
for y in recursive(x):
yield y
except TypeError:
yield coll
def test():
t = [[1,2,3], 4, 5, [6, [7, 8], 9]]
for x in recursive(t):
print x