本文介绍了获取嵌套字典中所有键的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获得包含列表和字典的嵌套字典中的所有键的列表。
I want to get a list of all keys in a nested dictionary that contains lists and dictionaries.
我目前拥有此代码,但似乎缺少添加列表中的一些键以及副本添加了一些键。
I currently have this code, but it seems to be missing adding some keys to the list and also duplicate adds some keys.
keys_list = []
def get_keys(d_or_l, keys_list):
if isinstance(d_or_l, dict):
for k, v in iter(sorted(d_or_l.iteritems())):
if isinstance(v, list):
get_keys(v, keys_list)
elif isinstance(v, dict):
get_keys(v, keys_list)
else:
keys_list.append(k)
elif isinstance(d_or_l, list):
for i in d_or_l:
if isinstance(i, list):
get_keys(i, keys_list)
elif isinstance(i, dict):
get_keys(i, keys_list)
else:
print "** Skipping item of type: {}".format(type(d_or_l))
return keys_list
这只是一个空列表,并用键填充。 d_or_l是一个变量,并使用原始的dict来比较它。
This just takes an empty list and populates it with the keys. d_or_l is a variable and takes the original dict to compare it against.
推荐答案
这应该做的工作:
def get_keys(dl, keys_list):
if isinstance(dl, dict):
keys_list += dl.keys()
map(lambda x: get_keys(x, keys_list), dl.values())
elif isinstance(dl, list):
map(lambda x: get_keys(x, keys_list), dl)
为避免重复,您可以使用set,例如:
To avoid duplicates you can use set, e.g.:
keys_list = list( set( keys_list ) )
示例测试用例:
keys_list = []
d = {1: 2, 3: 4, 5: [{7: {9: 1}}]}
get_keys(d, keys_list)
print keys_list
>>>> [1, 3, 5, 7, 9]
这篇关于获取嵌套字典中所有键的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!