Take the 2-minute tour ×

how do i separate the keys of this dict into two separate lists?

score = {(13.5, 12.0): 10.5, (10.7, 19.3): 11.4, (12.4, 11.1): 5.3}

list1 = []
list2 = []

so that I can have these lists when I print them?

list1 = [13.5, 10.7, 12.4]
list2 = [12.0, 19.3, 11.1]

i've tried this but it doesn't work

for (a, b), x in score:
share|improve this question
This is the third question today with that same data structure -- the other two from the same user. Are you him as well, or is this a homework question you're both trying to solve? –  agf Apr 14 '12 at 6:28
@agf haha it's a she. We are in the same Python class, but coughs she didn't put too much effort on this I think? We've never talked to each other, but looking at her questions, she didn't even put up any codes that she has attempted in her questions... I think this site is more of a way to help you to troubleshoot problems on what you already have, but she seems like asking for solutions without even trying. Come on. –  rudster Apr 14 '12 at 6:41
hopes that she wont see this –  rudster Apr 14 '12 at 6:42
@agf what does the homework tag do? :s –  rudster Apr 14 '12 at 6:45
oh i didn't know about that! i'm pretty new here so yeah thanks, will use the tag in my future questions :-) –  rudster Apr 14 '12 at 6:47

4 Answers 4

up vote 5 down vote accepted

Your code is almost correct, just remove the , x.

Iterating over a dictionary iterates over its keys, not its keys and values. Since you only need the keys here, iterating over the dictionary is fine.

Alternatively, you could iterate over score.items() instead (or score.iteritems() only on Python 2).

share|improve this answer

You are iterating over the keys of the dictionary, but assigning to (key, value). To iterate over the key-value pairs you can use items or iteritems:

for (a, b), x in score.iteritems():

In this specific case you could use list comprehensions instead of an explicit loop:

list1 = [a for a, b in score]
list2 = [b for a, b in score]
share|improve this answer

Alternately, you can use a combination of zip and splat (the unpack)

>>> x, y = zip(*score.keys())
>>> x
(10.7, 12.4, 13.5)
>>> y
(19.3, 11.1, 12.0)
share|improve this answer
The .keys is unnecessary (though OK if you want to be explicit). If you're going to rewrite the code I think this is the way to go, though it's a bit tricky for a beginner. –  agf Apr 14 '12 at 6:33
Oh yeah, that's right. I always forget that iterating over dict yields keys by default. –  Praveen Gollakota Apr 14 '12 at 6:36

You have to properly loop over your keys

for (a, b) in score.keys():
share|improve this answer
No need for .keys() –  jamylak Apr 14 '12 at 6:31
It defaults to that, right -- but newcomers usually don't know and hence using .keys() reminds them of what they are actually accessing ;) –  cfedermann Apr 14 '12 at 6:32

Your Answer


