Use for loop for iteration.
my_dict = {"a": 1, "b": 2, "c": 3}
for key, value in my_dict.items():
print(key + " " + str(value))
for key in my_dict:
print(key + " " + str(my_dict[key]))
The first one iterates over items and gives you keys and values. The second one iterates over keys and then it is accessing value from the dictionary using the key.
Answer from fiveobjects on Stack OverflowUse for loop for iteration.
my_dict = {"a": 1, "b": 2, "c": 3}
for key, value in my_dict.items():
print(key + " " + str(value))
for key in my_dict:
print(key + " " + str(my_dict[key]))
The first one iterates over items and gives you keys and values. The second one iterates over keys and then it is accessing value from the dictionary using the key.
You can do this by turning the dictionary into a list comprised of only the values.
val = list(account_data.values())
Would give you ["44196397", "2545086098", "210623431"...]
Which you can then very easily iterate over in a for loop without needing to worry about the key at all.
I was iterating over a dictionary, (more specifically a Counter object) and only needed the values, so I did something like: "for vals in dictName.values():"
However, I got a relatively slow runtime and was trying out different things, and then I tried: "for key, vals in dictName.items()" and the runtime was halved.
So, my question is: Why is one way faster than the other? And how is it working internally?
If someone can shed some light or point me in the direction of documentation explaining this speedup, I would be grateful. Thank you