Dict Copy & Compare

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Mon Apr 30 23:14:18 EDT 2007


On Mon, 30 Apr 2007 12:50:58 -0500, Hamilton, William  wrote:

>> On quick question, how can I order a dict by the 'values' (not keys)
>> before
>> looping? Is that possible?
>> 
> 
> The easiest way I can think of is to create a new dict that's reversed.
> 
> reverseDict = {}
> for key in dict1:
>     if dict1[key] not in reverseDict:
>         reverseDict[dict1[key]]=[key]
>     else:
>         reverseDict[dict1[key]].append(key)
> 
> This gives you a dictionary that has the old dict's values as keys, and
> the old dict's keys as lists of values.  You can then sort the keys of
> this dict and do what you want with it.  Of course, the values in dict1
> have to be valid dictionary keys for this to work.  If they aren't, you
> may be able to get away with converting them to strings.


Oh man, maybe you need to re-think what you consider "easier".

for value in dict1.itervalues()
    do_something_with(value)


If you need the keys as well:

for key, value in dict1.iteritems()
    do_something_with(key, value)

If you need to process the values (say, sort them) first:

pairs = list(dict1.iteritems()) # or dict1.items()
pairs.sort()
for key, value in pairs:
    do_something_with(key, value)
    
I'll leave sorting by value instead of key as an exercise.



-- 
Steven D'Aprano 




More information about the Python-list mailing list