I have a dict and a list but I want to go over each element at the same time. The first element of the dict and the first element of the list, the second element of the dict and the second element of the list, the third element of the dict and the third element of the list, and so.
Asked
Active
Viewed 204 times
0
-
2This doesn't make sense; dictionaries are unordered, they don't have a "first element". What are you trying to achieve? – jonrsharpe Jul 24 '14 at 09:47
-
My bad, I meant to ask if I could have two structures and iterate over them at the same time. I'll update the title accordingly. – Dta Jul 24 '14 at 09:48
-
In the general case you can use [`zip`](https://docs.python.org/2/library/functions.html#zip), but note that when you iterate over a dictionary you iterate by default over its keys (and the order is not guaranteed to be stable). – jonrsharpe Jul 24 '14 at 09:51
-
Just curious, are the keys simply chosen randomly. If not, how are they chosen? – Dta Jul 24 '14 at 09:52
-
1No, you define what the keys (and values) are. See [the tutorial](https://docs.python.org/2/tutorial/datastructures.html#dictionaries). – jonrsharpe Jul 24 '14 at 09:53
-
@Dta Yes. The ordering of the keys is implementation defined, which for practical purposes means mostly random. You should use sorted(dict.keys()) for a stable view on the keys. – vz0 Jul 24 '14 at 09:57
-
I meant when you iterate over them. – Dta Jul 24 '14 at 09:57
1 Answers
2
Perhaps you're looking for zip:
for item1, item2 in zip(structure1, structure2):
do_something(item1, item2)

Rusty Rob
- 16,489
- 8
- 100
- 116
-
2He'll have to find a way to make sure the items in the dict are returned in a stable order. – Aaron Digulla Jul 24 '14 at 09:50