0

Is it possible to make a function that will return a nested dict depending on the arguments?

def foo(key):
    d = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, }
    return d[key]

foo(['c']['d']) 

I waiting for:

3

I'm getting:

TypeError: list indices must be integers or slices, not str

I understanding that it possible to return a whole dict, or hard code it to return a particular part of dict, like

if 'c' and 'd' in kwargs:
    return d['c']['d']
elif 'c' and 'e' in kwargs:
        return d['c']['e']

but it will be very inflexible

salius
  • 113
  • 7
  • Kindly check this link: [Is there a recursive version of the dict.get() built-in?](https://stackoverflow.com/questions/28225552/is-there-a-recursive-version-of-the-dict-get-built-in). The error you're getting is due to this expression- `['c']['d']`, which does not make sense. – tidakdiinginkan Apr 23 '20 at 06:43

3 Answers3

3

When you give ['c']['d'], you slice the list ['c'] using the letter d, which isin't possible. So what you can do is, correct the slicing:

foo('c')['d']

Or you could alter your function to slice it:

def foo(*args):
    d = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, }
    d_old = dict(d) # if case you have to store the dict for other operations in the fucntion
    for i in args:
        d = d[i]
    return d
>>> foo('c','d')
3
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
1
d = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, }
def funt(keys):
  val = d
  for key in keys:
    if val:
      val = val.get(key)
  return val

funt(['c', 'd'])

Additionally to handle key not present state.

utsavan
  • 155
  • 7
-1

One possible solution would be to iterate over multiple keys -

def foo(keys, d=None):
    if d is None:
        d = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, }
    if len(keys) == 1:
        return d[keys[0]]
    return foo(keys[1:], d[keys[0]])

foo(['c', 'd']) 
Tom Ron
  • 5,906
  • 3
  • 22
  • 38