Chris
Chris

Reputation: 5814

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.

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

Upvotes: 0

Views: 47

Answers (3)

unwind
unwind

Reputation: 399979

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:

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.

Upvotes: 2

greole
greole

Reputation: 4771

eval can do this

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

Upvotes: 0

fredtantini
fredtantini

Reputation: 16566

You can use eval, but you have to be sure that the string does contain things you want:

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

Upvotes: 0

Related Questions