jumpman8947
jumpman8947

Reputation: 279

Iterate through dictionary, list within list

I have a dictionary which contains a list inside of lists. For example

d1 = {
    'first': [['soccer'], 2],
    'second': [['football'], 10],
    'third': [['basketball'], 5],
    'fourth': [['rugby'], 3]
}

Before I added the numbers to this dictionary I would just iterate through them like so

for k,v in d1.iteritems()
#Here i can separate all the keys and values as I wish

But now i need the numbers inside of the dictionary, so im trying to figure out how i can iterate through the current dict as is and be able to pull out the key, and the two values, For example if i were to try and do this

print k, value1, value2
# Output should be  first, soccer, 2

Upvotes: 0

Views: 57

Answers (1)

Randy
Randy

Reputation: 14847

If the format is consistent, you can just unpack it as you iterate through the dictionary:

In [5]: for k, ([sport], num) in d1.iteritems():
   ...:     print k, sport, num
   ...:
second football 10
fourth rugby 3
third basketball 5
first soccer 2

Upvotes: 3

Related Questions