Fisher Coder
Fisher Coder

Reputation: 3576

How to sort a dict by one of its values in Python?

I have a dict like this: key is a string, value is a list of strings

    my_dict = {
    'key1': [value11, value12, value13],
    'key2': [value21, value22, value23],
    'key3': [value31, value32, value33],
    'key4': [value41, value42, value43]
}

e.g.

dict_0 = {
'key1' : [lv, 2, abc],
'key2' : [ab, 4, abc],
'key3' : [xj, 1, abc],
'key4' : [om, 3, abc],
}

I wanted to be sorted based on the second value in the value list, so, it should be like this:

dict_0 = {
'key3' : [xj, 1, abc],
'key1' : [lv, 2, abc],
'key4' : [om, 3, abc],
'key2' : [ab, 4, abc],
}

I want to sort this dict by one of the value in the value list, i.e. value*2, how can I do this? I've searched extensively on the site, but didn't find a similar case.

Thanks.

Upvotes: 0

Views: 136

Answers (2)

Forhadul Islam
Forhadul Islam

Reputation: 1237

You could use:

sorted(d.items(), key=lambda x: x[1])

This will sort the dictionary by the values of each entry within the dictionary from smallest to largest.

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107287

Dictionaries are not ordered data structures, if you want a sorted one you can use OrderedDict() function from collections module.

>>> dict_0 = {
... 'key1' : ['lv', 2, 'abc'],
... 'key2' : ['ab', 4, 'abc'],
... 'key3' : ['xj', 1, 'abc'],
... 'key4' : ['om', 3, 'abc'],
... }

>>> from collections import OrderedDict
>>> OrderedDict(sorted(dict_0.items(), key=lambda x: x[1][1]))
OrderedDict([('key3', ['xj', 1, 'abc']),
             ('key1', ['lv', 2, 'abc']),
             ('key4', ['om', 3, 'abc']),
             ('key2', ['ab', 4, 'abc'])])
>>> 

Upvotes: 6

Related Questions