0 votes

loop through a dictionary and list simultaneously in re-italics in python

I have been in this for several weeks without success, the objective is through the list to recorer the dictionary or to check until the message you lose, you win or klk appears at the end of the dictionary using only the elements of the list

 dic = {  
  'a':{ 'b': {'c': 'You win'}},
  'x':{ 'y':{'z': 'You lose'}},
  'r':{ 'q':{'s': 'Klk manin'}}
}

a = ['x','y','z']

dic1 = dic['x']
dic2 = dic1['y']
dic3 = dic2['z']
print(dic3)

Thanks in advance

0voto

As I understand it you want to go through a dictionary based on a list of keys, and return the resulting value of the key indexing string to the dictionary.

 dic = {  
  'a':{ 'b': {'c': 'You win'}},
  'x':{ 'y':{'z': 'You lose'}},
  'r':{ 'q':{'s': 'Klk manin'}}
}

a = ['x','y','z']

def key_list_indexing(key_list, dic):
    curr_dic = dic
    for key in key_list:
        curr_dic = dic[key]
    return curr_dic


print(key_list_indexing(a, dic))
# imrpime 'you lose'

-1voto

Sr1871 Points 3160

You can use recursion

 dic = {  
  'a':{ 'b': {'c': 'You win'}},
  'x':{ 'y':{'z': 'You lose'}},
  'r':{ 'q':{'s': 'Klk manin'}}
}

def iterate(dict_to_iterate) :
    for key, value in dict_to_iterate.items() :
        if isinstance(value, dict) :
            iterate(value)
        else :
            print(value)


iterate(dic)

basically what is done is to check if it is a dictionary, if it is, the same function is used until it is a text, here you can know more about repulsive functions in python

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X