-2

Hi :) I am currently working on a Python project, and I have a dictionary with key-value pairs. I need to iterate over the dictionary and perform some operations based on both the keys and values. However, I'm kind of unsure of the best approach to do this. Could someone please guide me on how to iterate over a dictionary in Python while accessing both the keys an values? I would appreciate any code examples or suggestions on the most efficient and Pythonic way to accomplish this!

1 Answers1

-1

I would do it in this way:

for key in my_dict.keys():
    print(key, my_dict[key])
FordPrefect
  • 320
  • 2
  • 11
  • 1
    Iterating over `my_dict.items()` is a bit faster, especially for larger dictionaries. See the top-voted comment on this answer: https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops#comment77700753_3294899 – slothrop Jun 06 '23 at 18:17
  • Thanks for feedback. Do you have a measure how much faster it is? – FordPrefect Jun 06 '23 at 18:18
  • 1
    It depends on exactly what's in the dict (specifically, how long `__hash__` takes for the keys). But in a quick, not super-rigorous test with a simple dict of 10 million pairs of ints, it seems 10-20% slower using `.keys()`: [Try it online!](https://tio.run/##dY7RCoIwFIbv9xQHr7ZScXYn9CQRYjVtTDeZJ0GkZ1/TKEHrwDk35/8@/nbAu9EH52TTGouAshGkLmwl8pu8IhxhVBmoPYfSWFAgNdhCV4LyJE@SedmTEEx8cmLj6VBG5nQI/QQsuliiaDrKMgJ@ihAuHptiBPkvwYpWYvjCvc8vr5M6b5XpSklaKzXSMhi5r72jyCP07aHp4NFJXUFtTAumFxY@RQO2gdII@R/o3S9gzr0A "Python 3 – Try It Online") – slothrop Jun 06 '23 at 18:30
  • this is very unidiomatic. If you are going to iterate over the keys, don't use `.keys()`, just use `for key in my_dict:...` but you want to iterate over key-value pairs, so you should just use `for key, value in my_dict.items():` – juanpa.arrivillaga Aug 10 '23 at 19:57