Using tuples to eliminate multiple dict values

Tim Chase python.list at tim.thechases.com
Fri Sep 16 19:48:40 EDT 2011


On 09/16/11 13: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' }
> (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?

You could use something like

  d = dict(
    (k,v)
    for keys in (
      ((1,2,3), 'text'),
      ((5,6,7), 'other text'),
      )
    for k in keys
    )

which seems to do what you want with minimal redundancy of 
declarations.

-



More information about the Python-list mailing list