访问python dict与多个键查找字符串 [英] Accessing python dict with multiple key lookup string

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

问题描述

我正在寻找在python中创建一个简单的查找机制,并希望确保在python的大型库中没有隐藏的东西,在创建它之前还没有这样做。



我正在寻找格式如此的格式的

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

我试图有一种方法来访问数据通过使用类似于

  root.secondary.user2 

,并将该结果命令作为响应返回。我认为必须有一些这样做,我可以写一个没有太多困难,但我想确保我没有重新创建我可能会从文档中丢失的东西。谢谢

解决方案



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

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

这个漏洞利用了字典中查找密钥 k d 可以写成 dict.get(d,k)



修改:为了完整性,使用以下方法获取,设置或删除字典键的三个功能:

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


I am looking to create a simple "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.

I am looking to take a dict that is formatted something like this

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

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天全站免登陆