Tricky Dictionary Question from newbie

Ric Da Force ric at next-level.com.au
Mon Jul 11 22:24:04 EDT 2005


How does setdefault work exactly? I am looking in the docs and can't figure 
it out...
Ric

"Ric Da Force" <ric at next-level.com.au> wrote in message 
news:dav1ui$nn2$1 at nnrp.waia.asn.au...
> Thank you guys! (Reinhold, Mark and Markus)  I must confess that I am 
> absolutely awe struck at the power of this language!  There is no way in 
> the world that I would have envisaged such simple and elegant solutions!!!
>
> Reinhold, is your solution specific to 2.4?
>
> Kind Regards,
>
> Ric
>
> "Reinhold Birkenfeld" <reinhold-birkenfeld-nospam at wolke7.net> wrote in 
> message news:3jftckFpvhv2U2 at individual.net...
>> Mark Jackson wrote:
>>> "Ric Da Force" <ric at next-level.com.au> writes:
>>>
>>>> It is hard to explain but this is what I mean:
>>>>
>>>> Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This 
>>>> is
>>>> not'}
>>>>
>>>> I want this to return a new dict with string keys and lists containing 
>>>> the
>>>> previous keys for repeated values.
>>>>
>>>> NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']}
>>>
>>> NewDict = {}
>>> for x in Dict.keys():
>>> try:
>>> NewDict[Dict[x]].append(x)
>>> except KeyError:
>>> NewDict[Dict[x]] = [x]
>>
>> Or, more up-to-date:
>>
>> NewDict = {}
>> for key, val in Dict.iteritems():
>>    NewDict.setdefault(val, []).append(key)
>>
>> Reinhold
>
> 





More information about the Python-list mailing list