Accessing python dict using nested key lookup string

前端 未结 3 834
傲寒
傲寒 2020-12-30 05:12

I am looking to create a simple nested \"lookup\" mechanism in python, and wanted to make sure there wasn\'t already something somewhere hidden in the vast libraries in pyth

3条回答
  •  长发绾君心
    2020-12-30 05:44

    There's nothing in the standard library for this purpose, but it is rather easy to code this yourself:

    >>> key = "root.secondary.user2"
    >>> reduce(dict.get, key.split("."), my_dict)
    {'age': 25, 'name': 'fred'}
    

    This exploits the fact that the look-up for the key k in the dictionary d can be written as dict.get(d, k). Applying this iteratively using reduce() leads to the desired result.

    Edit: For completeness three functions to get, set or delete dictionary keys using this method:

    def get_key(my_dict, key):
        return reduce(dict.get, key.split("."), my_dict)
    
    def set_key(my_dict, key, value):
        key = key.split(".")
        my_dict = reduce(dict.get, key[:-1], my_dict)
        my_dict[key[-1]] = value
    
    def del_key(my_dict, key):
        key = key.split(".")
        my_dict = reduce(dict.get, key[:-1], my_dict)
        del my_dict[key[-1]]
    

提交回复
热议问题