[Tutor] how to delete some quasi-duplicated keys

Steven D'Aprano steve at pearwood.info
Fri Nov 25 10:06:13 CET 2011


lina wrote:
>>>> pairs
> {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25}
> 
> 
> such as here ('66', '69') and ('69', '66') is one key,
> 
> I wanna keep only one and add the value of those two keys, above is a
> very simple example:


Which one do you want to keep?

If the order ('66', '69') is unimportant, you should use a frozenset 
instead of a tuple. In your code, where you set the pairs in the first 
place, instead of doing:

pair = ('66', '69')  # however you build the pair
pairs[pair] = value

(or how ever you set the initial values), change it to this:

pair = frozenset(('66', '69'))
pairs[pair] = pairs.get(pair, 0) + value




-- 
Steven



More information about the Tutor mailing list