Using tuples to eliminate multiple dict values

MRAB python at mrabarnett.plus.com
Fri Sep 16 21:29:41 CEST 2011


On 16/09/2011 19:47, Benshep wrote:
> I need a dictionary that returns the same value for multiple keys.
>
> i.e.
>
> (1)>>>  dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' }

That will create a dict with 2 keys, both of which are tuples.

> (2)>>>dict[1]
> (3)   'text'
>
> I cant figure out what i need on line 2 to make this scenario work. Is
> there a simple way to check if the a number is present in the key and
> then return the value?
>
If you want multiple keys, then you must provide them separately:

my_dict = {1: 'text', 2: 'text', 3: 'text', 5: 'other text', 6 : 'other 
text', 7: 'other text'}

or use 'for' to iterate through the keys for each value:

my_dict = dict([(k, 'text') for k in (1, 2, 3)] + [(k, 'other text') for 
k in (5, 6, 7)])

or something similar.



More information about the Python-list mailing list