简体   繁体   中英

Python: sorting items in a dictionary by a part of a key?

Say I have a dictionary of kings with roman numerals in their names as the key, the roman numerals in integer form as the values.

d = {'Zemco III': 3, 'Usamec XL': 40, 'Usamec VII': 7, 'Robert VIII': 8, 'Usamec XLII': 42, 'Mary XXIV': 24, 'Robert III': 3, 'Robert XV': 15, 'Usamec XLIX': 49}

I would like to sort the list from oldest to youngest, that is Usamec XLII should come before Usamec XLIX. I would also like to sort the list alphabetically, that is the Usamec XLII should come before Zemco III.

My approach was to sort by name first, then by roman numeral value as such:

x = sorted(d.items(),key=operator.itemgetter(0))
y = sorted(x,key=operator.itemgetter(1))

However, because the roman numerals are part of the key, my alphabetical sort does not work as intended. My question is, can I sort the dictionary by a part of the key, for example if my key is Zemco III, can I sort my items somehow with key.split()[0] instead of the entire key? Thanks!

key is just a function that receives an item and returns what you need to sort on. It can be anything.

This sorts the items by the (name_without_rightmost_word, number) key:

In [92]: sorted(d.items(), key=lambda (name, num): (name.rsplit(None, 1)[0], num))
Out[92]:
[('Mary XXIV', 24),
 ('Robert III', 3),
 ('Robert VIII', 8),
 ('Robert XV', 15),
 ('Usamec VII', 7),
 ('Usamec XL', 40),
 ('Usamec XLII', 42),
 ('Usamec XLIX', 49),
 ('Zemco III', 3)]

If you use python 3, use this key :

lambda item: (item[0].rsplit(None, 1)[0], item[1])

key.rsplit(None, 1)[0] is better than key.split()[0] in case of multiword names.

To just get it sorted you can do this:

sorted_stuff = sorted([(ord(x[0]), x, y) for x, y in d.items()])
final_sorted = [(y,z) for x,y,z in sorted_stuff]

The sorted_stuff will look like this:

[(77, 'Mary XXIV', 24), (82, 'Robert III', 3)]

The final_sorted will be formatted properly:

[('Mary XXIV', 24), ('Robert III', 3)]

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