简体   繁体   English

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

[英]How to get all dict keys-values in python?

I have dict like this in a function:我在函数中有这样的dict:

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

In one function1 where I call only a part of this config.在一个函数 1 中,我只调用了这个配置的一部分。 So I call it like my_func('key1') .所以我把它my_func('key1') And I have function2, where I want to get all the dictionary.我有function2,我想在其中获取所有字典。 Can I get it without for cycle?我可以在没有循环的情况for得到它吗?

By using a recursive approach together with functional progrmaming to avoid loops:通过使用递归方法和函数式编程来避免循环:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM