如何在python中获得所有dict键值?



我在函数中有这样的dict:

def my_func(key):
dictionary = 
{
'key1':
{'some_key': 'some_val'},
'key2':
{'some_key': 'some_val'}
}
return dictionary.get(key)

在一个函数1中,我只调用了这个配置的一部分。所以我叫它my_func('key1')。还有函数2,我想要得到整个字典。没有for循环我能得到它吗?

通过使用递归方法和函数式编程来避免循环:

dictionary = {'key1': {'some_key1': 'some_val1'}, 'key2': {'some_key2': 'some_val2'}}
def my_func(key, dictionary):
if key in dictionary:
return dictionary[key]
return next(filter(None, map(lambda d: my_func(key, d) if isinstance(d, dict) else None, dictionary.values())), None)
a = my_func('some_key2', dictionary)
# some_val2
a = my_func('not a key', dictionary)  # if key is wrong
# None

最新更新