Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over dictionaries containing tuples

I have a dictionary, the values of which are tuples. I want to be able to iterate over the key and every individual element in the value tuple, rather than the tuple object itself. Here's my code:

keys = ['a','b','c']
values = [(0,1,2),(3,4,5),(6,7,8)]
mydict = dict(zip(keys,values))

Now at this point, I'd like to do something like the following:

for key,num1,num2,num3 in mydict.iteritems():
    print key,num1,num2,num3

It turns out that I can only pull out the tuple value itself, not the individual elements. How would I be able to iterate over each element of the tuple?

Thank you!

like image 219
user1636547 Avatar asked Oct 14 '25 04:10

user1636547


1 Answers

>>> for key, (num1, num2, num3) in mydict.iteritems():
...     print key, num1, num2, num3
... 
a 0 1 2
c 6 7 8
b 3 4 5

Using parens allows you to unpack the values.

like image 144
Jared Avatar answered Oct 18 '25 23:10

Jared