Python sorts multiple attributes

I have a dictionary like the following. Value pair or username: name

d = {"user2":"Tom Cruise", "user1": "Tom Cruise"}

My problem is that I need to sort them by name, but if multiple users contain the same name as above, I need to sort them by username. I looked at the sorted function, but I really don't understand the cmp parameter and lambda. If someone can explain this and help me with this, it will be great! Thank:)

+3
source share
3 answers

cmpbecomes obsolete. lambdajust performs a function.

sorted(d.iteritems(), key=operator.itemgetter(1, 0))
+6
source

-. cmp . . key.

lambda . , def , .

my_func = lambda x: x + 1

, , x x + 1. lambda x, y=1: x + y , x, y 1 x + y. , , def, , .

key , sorted , .

list_ = ['a', 'b', 'c']
sorted(list_, key=lambda x: 1)

. , . , . ,

  • dict s. dicts s? .
  • username.

a > , -

users = [{'name': 'Tom Cruise', 'username': user234234234, 'reputation': 1},
         {'name': 'Aaron Sterling', 'username': 'aaronasterling', 'reputation': 11725}]

, , , :

sorted(users, key=lambda x: x['reputation'])

, 'reputation' . lambdas . operator.itemgetter - , .

operator.itemgetter , .

f = operator.itemgetter('name', 'username') , lambda d: (d['name'], d['username']) , , lambda.

, dict ,

sorted(list_of_dicts, operator.itemgetter('name', 'username'))

, -.

+5

, dict . python 2.7 3.1 . OdderedDict.

,

>>> from collections import OrderedDict
>>> d=OrderedDict({'D':'X','B':'Z','C':'X','A':'Y'})
>>> d
OrderedDict([('A', 'Y'), ('C', 'X'), ('B', 'Z'), ('D', 'X')])
>>> OrderedDict(sorted((d.items()), key=lambda t:(t[1],t[0])))
OrderedDict([('C', 'X'), ('D', 'X'), ('A', 'Y'), ('B', 'Z')])
0

Source: https://habr.com/ru/post/1777350/


All Articles