0 votes

Looping in dictionaries

I have a problem with dictionaries in python.

How do I get the key of a dictionary from the value?

That is, if I had a dictionary of the form;

 d={"key1":
  {"key2":
  {"e":5,"f":8,....,"z":10}}}

and I want to know which key contains the value 50.

0voto

Marcelo Points 26
d={"key1":{"key2":{"e":5,"f":8,"z":10}}}

def buscar(d, criterio, p = ""):
    for k, v in d.items():
        if isinstance(v, dict):
            buscar(v, criterio, "{} > {}".format(p, k))
        elif v == criterio:
            print("{} > {} : {}".format(p, k, v))

buscar(d, 10)

The result would be:> key1> key2> z: 10

Greetings

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