简体   繁体   中英

Sorting dict using tuple or list in Python

How can I sort dict keys using a tuple or a list and than return values? For example, I have a dict:

d = {'a' : 1, 'b' : 3, 'c' : 5, d : '7'}

and a tuple:

t = ('d', 'b', 'c', 'a')

I would like to get a list of values, like:

[7, 3, 5, 1]

Many thanks!

You can use a list comprehension:

>>> [d[k] for k in t]
['7', 3, 5, 1]

or map :

>>> map(d.get, t)
['7', 3, 5, 1]

You can also create an OrderedDict using the items in t :

>>> from collections import OrderedDict
>>> dic = OrderedDict((k, d[k]) for k in t)
>>> dic.values()
['7', 3, 5, 1]

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