简体   繁体   中英

Sort list of dictionary items based on custom comparator in python

I have a dictionary of values that I want to sort based on my own defined comparisons. I know you can't sort dictionaries. Here's the important code:

def cmpFirstVals(tup1,tup2):
  if tup1[0] > tup2[0]:
    return True
  else:
    return False
def cmpSecondVals(tup1,tup2):
  if tup1[1] > tup2[1]:
    return True
  else:
    return False

So the two comparison functions take in two tuples of two ints. It compares the two tuples and returns true if the first is higher, so (0,4) would be higher than (0,3) if using the second comparator. Likewise,

cmpFirstVals((4,2),(2,2))

would return True.

My dict is built with strings as keys and the two-int tuple as the values:

d = {'objA':(1,12),'objB':(13,3)} //etc etc etc

I know it's possible to sort the list d.items(), and I would ultimately construct a dict with the top three items in the sorted list, but I need to use these comparators for the sorting.

I need to know how would I sort via these comparators?

Also, note that the comparators would return false if the two tuples had the same index values. (ie cmpFirstVals((4,2),(4,3)) would return false)

Erm...

byfirst = sort(somedict.values(), key=operator.itemgetter(0))
bysecond = sort(somedict.values(), key=operator.itemgetter(1))

Binary comparators are deprecated in 2.x, and removed in 3.x.

If you want your sorted list to only contain the value tuples:

>>> d = {'objA':(1,12),'objB':(13,3)}
>>> sorted(d.values())
[(1, 12), (13, 3)]
>>> sorted(d.values(), key=lambda t: t[1])
[(13, 3), (1, 12)]

If you want the full tuple of the value in the dict:

>>> sorted(d.items(),key=lambda t: t[1][1])
[('objB', (13, 3)), ('objA', (1, 12))]
>>> sorted(d.items(),key=lambda t: t[1][0])
[('objA', (1, 12)), ('objB', (13, 3))]

Edit (based on your comment):

def f(d,c):
    return sorted(d.items(),key=c) 

print(f(d,lambda t: t[1][0]))  

The key accepts a function. So you can do this:

def cmpFirstVal(t1):
    return t1[1][0]

def cmpSecondVal(t1):
    return t1[1][1]

def f(d,c):
    return sorted(d.items(),key=c) 

print(f(d,cmpFirstVal)) 
print(f(d,cmpSecondVal)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM