Using tuples to eliminate multiple dict values

Chris Angelico rosuav at gmail.com
Sat Sep 17 01:19:53 CEST 2011


On Sat, Sep 17, 2011 at 4:47 AM, Benshep <ben.r.shepherd at gmail.com> wrote:
> (1)   >>> dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' }
>

As I understand it, you're looking for a simple syntax for what MRAB posted:
> my_dict = {1: 'text', 2: 'text', 3: 'text', 5: 'other text', 6 : 'other text', 7: 'other text'}

Since your first line of code is syntactically legal, you could do a
simple check afterwards to translate it:

my_dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' }
for k in list(my_dict.keys()):
    if isinstance(k,tuple):
        val=my_dict.pop(k)
        for i in k: my_dict[i]=val

Tested in Python 3.2; in Python 2, the list() call is superfluous,
everything else should work fine.

Chris Angelico



More information about the Python-list mailing list