A dict
dic = {
1: 'a',
2: 'a',
3: 'b',
4: 'a',
5: 'c',
6: 'd',
7: 'd',
8: 'a',
9: 'a'}
I want to remove duplicate values just keep one K/V pair,
Regarding the “key” selection of those duplicated values, it may be max or min or by random select one of those duplicated item’s key.
I do not want to use a k/v swap since that can not control the key selection.
Take value “a” for example
1: 'a',
2: 'a',
4: 'a',
8: 'a',
9: 'a'
the max key will be {9: ‘a’} and the min will be {1: ‘a’}, and the random will choise any one of it.
And, if the key is other kind of hashable value, for example, string, then how to do such a selection?
Can anyone share me an idea?
Thanks!
Or other “selection” functions in lieu of
min(which, of course, does work fine even if keys are strings — will give you the “lexically first” key in that case).The one case in which the selection function needs some care is when the keys corresponding to the same value may be non-comparable (e.g., complex numbers, or, in Python 3, objects of different not-all-numeric types). Nothing a
key=in theminwon’t cure;-).