Accessing python dict using nested key lookup string

前端 未结 3 819
傲寒
傲寒 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:38

    Recursion still works.

    def walk_into( dict, key ):
        head, _, tail = key.partition('.')
        if tail:
            return walk_into( dict[head], tail )
        return dict, key
    d, k = walk_into( my_dict, "root.secondary.user2" )
    

    d[k] can be used for getting or putting a new value.

提交回复
热议问题