I will not touch on the difference between list.sort () and sorted (). It seems that you can write like this about the specification of the key to sort. 2.7, maybe 3 and later.
python2.7
from pprint import pprint
items = [
{'id':2, 'book': {'type':'zassi', 'name': u'bbb' }},
{'id':3, 'book': {'type':'manga', 'name': u'ccc' }},
{'id':4, 'book': {'type':'zassi', 'name': u'ddd' }},
{'id':1, 'book': {'type':'manga', 'name': u'aaa' }},
{'id':5, 'book': {'type':'manga', 'name': u'eee' }},
]
#One sort key
sorted_items = sorted(
items,
key = lambda x: x['id']
)
pprint(sorted_items)
#=>
#[{'book': {'name': u'aaa', 'type': 'manga'}, 'id': 1},
# {'book': {'name': u'bbb', 'type': 'zassi'}, 'id': 2},
# {'book': {'name': u'ccc', 'type': 'manga'}, 'id': 3},
# {'book': {'name': u'ddd', 'type': 'zassi'}, 'id': 4},
# {'book': {'name': u'eee', 'type': 'manga'}, 'id': 5}]
#Two or more sort keys
sorted_items = sorted(
items,
key = lambda x: (x['book']['type'], x['id'])
)
pprint(sorted_items)
#=>
#[{'book': {'name': u'aaa', 'type': 'manga'}, 'id': 1},
# {'book': {'name': u'ccc', 'type': 'manga'}, 'id': 3},
# {'book': {'name': u'eee', 'type': 'manga'}, 'id': 5},
# {'book': {'name': u'bbb', 'type': 'zassi'}, 'id': 2},
# {'book': {'name': u'ddd', 'type': 'zassi'}, 'id': 4}]
I wrote later and noticed that item getter and attr getter seem to only look at the same hierarchy, so for example, [{book: {}, shelf: {}}, {book: {}, shelf: {} }] With a structure like
, I feel that it is not possible to specify keys like this for books and this for shelves. </ del>-> You can specify these with tuples without using them.
Recommended Posts