0

I am a little new to python and need help in this,

dict_o = {'chamcham': 200,
          'kajukatli': 400,
          'jalebi': 1000,
          'chowmen': 1500,
          'outsourced':{'samosa': 200,
                      'mungfali': 400,
                      'springrolls': 1000,
                     'chomen': 1800}}

I want the values which are provided in a list like

list = ['chamcham',"['outsourced']['springrolls']"]

(specifying this way a list is a wrong syntax).

in other words, how to we get the value against 'chamcham' and 'springrolls' which is a nested key in the 'outsourced' nested dictionary. the keys of which value is required is a list?

I have referred to How to retrieve values from nested dictionary given list of keys? but this works only when list has nested elements only and not a combination of nested and first level keys.

Ajay Singh Rana
  • 573
  • 4
  • 19
Gupta
  • 314
  • 4
  • 17

1 Answers1

0

You could modify the way you are storing the values into two different lists and dictionaries and it would be better that way but as you want a solution for this so lets' change your list a bit:

dict_o = {'chamcham': 200,
          'kajukatli': 400,
          'jalebi': 1000,
          'chowmen': 1500,
          'outsourced':{'samosa': 200,
                      'mungfali': 400,
                      'springrolls': 1000,
                     'chomen': 1800}}
items = ['chamcham',['springrolls']]    # you need not store outsourced things as a string store these as another list and prevent from using python function names as vairable names

# now iterate thorugh the list and get the values from the dictionary
for item in items:
    if(type(item) == list):    # checks if item is a list or not
        for i in item:
            try:
                print(dict_o['outsourced'][i])
            except KeyError:
                print(f'{i} not available.')
    else:
        try:
            print(dict_o[item]
        except KeyError:
            print(f'{item} is not available.')
Ajay Singh Rana
  • 573
  • 4
  • 19