Dictionary in dictionaries

1

I have a dictionary that in turn contains dictionaries that look something like this:

variable={'query': {'query_string': {'query': 'E.keyword: {sustituir_0}'}}}

The idea is to create a function that obtains the keys of each dictionary and returns them in an array, to later change {substitute_0} for the desired word.

The function used is recursive and it is this

def funcion_recursiva(diccionario,resultados=None): 
    if resultados is None: 
        resultados = [] 
    if (type(diccionario)==str): 
        return resultados 
    elif (type(diccionario)==dict):
        clave=diccionario.keys()[0] 
        resultados.append(clave) 
    return funcion_recursiva(diccionario[clave],resultados)

We apply the function to our variable

resul = funcion_recursiva(variable)

and we try to apply a for loop to advance in the dictionary

z=''
for i in range(len(resul)):
    z=z+"["+resul[i]+"]"
    if(i==range(len(resul))-1):
       variable[z]=variable[z].replace('{sustituir_0}',"Madrid")

This is where my error comes from and my question when I do variable [z] it gives me an error and if I try to concatenate too.

If I have all the dictionary keys in dictionaries in a list, how can one access the dictionary fields using the for loop?

    
asked by Javi 22.10.2018 в 12:37
source

1 answer

0

You can initialize a variable aux with the dictionary variable and make a loop that iterates over the keys you have in the list resul , except the last one. In each iteration you substitute aux for the value you read of the corresponding key.

Leaving the loop aux would be pointing to the most internal dictionary of all, on which you could already perform the desired operation:

aux = variable
for k in resul[:-1]:
  aux = aux[k]
last_key = resul[-1]
aux[last_key] = aux[last_key].replace("{sustituir_0}","Madrid")

That change affects the original variable:

print(variable)
{'query': {'query_string': {'query': 'E.keyword: Madrid'}}}

Update

Moreover, you can save the recursive function that previously created the list of tags, and use the aux trick to go through the dictionary until you reach the level where the stored values are strings:

aux = variable
while type(list(aux.values())[0]) == dict:
  aux = list(aux.values())[0]

When leaving this loop you have aux as in the previous case, pointing to the most internal dictionary.

( Note I have put list(aux.values()) to work also under Python3, because in this version dict.values() does not return a list, but an iterator, and it would not be possible to access its element [0] )

    
answered by 22.10.2018 в 13:00