使用嵌套键查找字符串访问python dict [英] Accessing python dict using nested key lookup string

查看:110
本文介绍了使用嵌套键查找字符串访问python dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在python中创建一个简单的嵌套查找"机制的方法,并希望确保python的庞大库中没有隐藏的东西在创建它之前就没有这样做.

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 python that doesn't already do this before creating it.

我希望采用这样的格式

my_dict = { 
  "root": { 
    "secondary": { 
      "user1": { 
          "name": "jim", 
          "age": 24 
      }, 
      "user2": { 
        "name": "fred", 
        "age": 25 
      } 
    } 
  } 
}

我正在尝试一种使用类似于十进制表示法的十进制表示法访问数据的方法.

and I am trying to have a way to access the data by using a decimal notation that would be something similar to

root.secondary.user2

并将返回的结果字典作为响应返回.我认为必须有某种方法可以做到这一点,并且我可以很容易地编写一个,但是我想确保自己不会重新创建文档中可能缺少的内容.谢谢

and return that resulting dict back as a response. I am thinking that there must be something that does this and I could write one without much difficulty but I want to make sure I am not recreating something I might be missing from the documentation. Thanks

推荐答案

为此目的,标准库中没有任何内容,但是您自己编写代码很容易:

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'}

这利用了以下事实:在字典d中对键k的查找可以写为dict.get(d, k).使用reduce()反复应用此操作可获得预期的结果.

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]]

这篇关于使用嵌套键查找字符串访问python dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆