简体   繁体   English

如何在仅包含字符串的字典中获取字典中的值?

[英]How to get a value within a dictionary within a dictionary with just a string?

I'm trying to create a function that takes in a dictionary and a string and outputs a value within the Dictionary depending on the string. 我正在尝试创建一个函数,该函数接受字典和字符串,并根据字符串在Dictionary中输出值。

For example, inputs would be: 例如,输入为:

D = {'assigned':{'id':4,'name':'myname'},'anotherkey':{'id':4,'name':'myname'}}
s = "['assigned']['id']"

Result: 结果:

4 

This can also be achieved with the following, but the issue is that the function will only take a dictionary and a string 这也可以通过以下方式实现,但问题是该函数将仅使用字典和字符串

print D['assigned']['id']
>> 4

If you don't want to use eval() , you can of course parse out the fields of the string yourself, using regular expressions for instance: 如果您不想使用eval() ,那么当然可以使用正则表达式自己解析字符串的字段:

import re

def lookup(d, s):
  mo = re.match(r"\['([a-z]+)'\]\['([a-z]+)'\]", s)
  if mo and len(mo.groups()) == 2:
    return d[mo.group(1)][mo.group(2)]
  return None

You can do simpler parsing too since the input is pretty fixed. 您也可以进行更简单的解析,因为输入是非常固定的。

You can use eval , but you have to be sure that the string does contain things you want: 您可以使用eval ,但是必须确保该字符串确实包含您想要的东西:

>>> eval("D"+s)
4

eval can do this eval可以做到这一点

>>> D = {'assigned':{'id':4,'name':'myname'},'anotherkey':{'id':4,'name':'myname'}}
>>> s = "['assigned']['id']"
>>> eval("D" +s)
4

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

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