Question

Suppose I have this nested dictionary as below. Is there a pythonic way of iterating over keys and values of both outer and inner dictionaries simultaneously?

I currently perform:

for outer_key, outer_value in outer.items():
    for inner_key, inner_value in outer_value.items():
        #my required processing

Just want to know if there is any better, faster way to do this? Faster in the sense of using dict comprehensions, speedier execution than the normal method, memory savings etc (when it is applied to huge dicts)?

{'68299-6030-885-42-4-54603-20645-15734': {'0-0-0-0-0-0-0-0': {'service_latency': 9.815000000000001, 
                                                               'service_cost': 58.78,     
                                                               'service_bandwidth': 247.36}}, 
 '68299-6030-885-431-43303-80233-26504-15734': {'0-0-0-0-0-0-0-0': {'service_latency': 10.706, 
                                                                    'service_cost': 50.06, 
                                                                    'service_bandwidth': 362.88}}, 
 '68299-6030-885-42-79805-13540-5668-15734': {'0-0-0-0-0-0-0-0': {'service_latency': 12.66, 
                                                                  'service_cost': 75.19, 
                                                                  'service_bandwidth': 707.74}}, 
 '68299-6030-90241-3290-2033-5668-15734': {}, 
 '68299-73365-46658-104-10-6685-29853-44799': {'0-0-0-0-0-0-0-0': {'service_latency': 12.427, 
                                                                   'service_cost': 44.949999999999996,  
                                                                   'service_bandwidth': 232.89}}}
Was it helpful?

Solution

  • some_dict.items() is appropriate method to get access to both keys and values simultaneously
  • the explicit nested loops in your code may be faster than the corresponding list/dict comprehensions on CPython
  • .items() on Python 3 doesn't create a list. It doesn't matter how huge your dict is: memory usage should be constant while you are iterating over .items()

.items() returns a view on Python 3. You shouldn't try to change outer, outer_value dictionaries while iterating over them.

Your code is fine as is if you can't change the input data structures.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top