简体   繁体   中英

Python: Python:Sort values in dictionary?

I have

x = {2:[40,30],3:[24,16],4:[30,2],5:[0,80],6:[19,8]}

and I need to sort dictionary based on the 1st item in the value so my result should be

{2:[40,30],4:[30,2],3:[24,16],6:[19,8],5:[0,80]}

All you need to do is using dict

d = dict(x)

Since your list is already in the right format to be easily converted to Dictionary , that is, you already have a key-value tuple pair as your list elements.

Simply pass it into dict() :

>>> dict([(2, [40, 30]), (4, [30, 2])])
{2: [40, 30], 4: [30, 2]}

Dictionaries don't care what order their values are in:

>>> {'one': 1, 'two': 2} == {'two': 2, 'one': 1}
True

If you want to maintain order, you can use collections.OrderedDict :

>>> from collections import OrderedDict
>>> OrderedDict([(2, [40, 30]), (4, [30, 2])])
OrderedDict([(2, [40, 30]), (4, [30, 2])])

You weren't explicit in your question, but from your comments on other answers you want to preserve the order of the list in dictionary form. A standard dictionary is inherently unordered, however, you can use an OrderedDict instead:

from collections import OrderedDict

x =  [(4, [30, 2]), (2, [40, 30])]
d = dict(x)
print(d)
# {2: [40, 30], 4: [30, 2]}

d = OrderedDict(x)
print(d)
# OrderedDict([(4, [30, 2]), (2, [40, 30])])

This preserves the keys in order of addition to the dictionary.

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