Search code examples
pythondictionaryflattendictionary-comprehension

Iterate nested python dictionary efficiently


I'm new to python. I have a nested dictionary like (k1,(t1,v1)). I would like to loop through each and every v1 values efficiently.

So lets say my dictionary is my_dict. I want to access k , x, y with out two for loops efficiently, using a flattener or a dictionary comprehension. Please let me know the best practice.

     for k, v in my_dict.iteritems():
         inner_dict = my_dict.get(k)
         for x, y in inner_dict.iteritems():
             print(k, x , y ) 

Solution

  • There's no need to loop over items if you're only interested in values:

    flattened_values = (v for dct in my_dict.itervalues() for v in dct.itervalues())
    for value in flattened_values:
        print(value)
    

    Edit:

    Based on your edit you do need the keys as well. In that case your code is fine apart from the redundant inner_dict = my_dict.get(k), which is basically v only. A one-liner for the same would look like this:

    for v in ((k1, k2, v2) for k1, v1 in my_dict.iteritems() for k2, v2 in v1.iteritems()):
        print(v)