1

I have the following python code:

print {a:b for a in [1, 2] for b in [3, 4, 5]}

which I would expect to give me something like this:

{1:3, 1:4, 1:5, 2:3, 2:4, 2:5}

But it instead gives me this:

{1: 5, 2: 5}

I've also tried it with the loops reversed like suggested here:

print {a:b for b in [3, 4, 5] for a in [1, 2]}

But it still gives me that wrong answer. And I've also tried the same comprehension in a list like so:

print [(a, b) for a in [1, 2] for b in [3, 4, 5]]

Which works exactly as expected.

What am I missing about dictionaries?

FYI, python command returns:

Python 2.7.4 (default, Apr 19 2013, 18:32:33) 
[GCC 4.7.3] on linux2
Community
  • 1
  • 1
blaineh
  • 2,263
  • 3
  • 28
  • 46

2 Answers2

5

Dictionaries have unique keys. You can't have the key 1 (for example) mapping to multiple values.

If you need to store multiple values against a key, store a list of values rather than a single value.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
2

What am I missing about dictionaries?

The keys are unique. You can read about dictionaries in the docs here:
http://docs.python.org/2/library/stdtypes.html#mapping-types-dict

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306