0

Let's say we have a dictionary inside a dictionary:

people = {
           0: {'name': 'John', 'age': 27, 'sex': 'Male'},
           4: {'name': 'Marie', 'age': 22, 'sex': 'Female'},
           7: {'name': 'Agness', 'age': 25, 'sex': 'Female'}
         }

What is a faster way to go through that dictionary? I saw on Internet solution:

for p_id, p_info in people.items():
    print("\nPerson ID:", p_id)        
    for key in p_info:
        print(key + ':', p_info[key])

However items function creates from scratch(?) a list of tuples.

I feel like going through dictionary that way is faster:

for key in people:
    for value in people[key]:
        print(value)

Am I wrong? If yes, why?

Morfidon
  • 1,469
  • 1
  • 18
  • 34
  • 1
    I think your best way would be benchmarking how long both take with the time module – Nick Dima Sep 05 '18 at 15:21
  • https://stackoverflow.com/questions/10458437/what-is-the-difference-between-dict-items-and-dict-iteritems – taras Sep 05 '18 at 15:22
  • 2
    I suppose you are using python2. In this case you have an equivalent method named `iteritems` that iterates over the key-value pairs, without creating the list. – Roberto Trani Sep 05 '18 at 15:23

0 Answers0