Reputation: 4928
MRE:
d = {"a": 1, "b":2, "c":3}
colors = ["red", "green", "blue"]
iterate dictionary key-value pairs by using:
for key, value in d.items():
print(key, value)
>>> a 1
>>> b 2
>>> c 3
However I want to combine it with colors list. This is what I desire:
for (key, value, color) in (d.items(), colors):
print(key, value, color)
>>> a 1 red
>>> b 2 green
>>> c 3 blue
How can I achieve this?
right now I am changing key, value into lists and then iterate through 3 lists
Upvotes: 0
Views: 30
Reputation: 4510
You can use zip
to iterate over more than one element at the same time like this:
d = {"a": 1, "b":2, "c":3}
colors = ["red", "green", "blue"]
for (key, value), color in zip(d.items(), colors):
print(key, value, color)
>>> a 1 red
>>> b 2 green
>>> c 3 blue
Upvotes: 2
Reputation: 8551
You need to use zip
, can you try the following:
for dd, cc in zip(d, colors):
print(dd, d[dd], cc)
Upvotes: 1