0

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.

Fisher Coder
  • 3,278
  • 12
  • 49
  • 84
  • Dictionaries are unordered. – frogatto Jul 08 '16 at 22:24
  • You can't sort a dictionary. A dictionary has hashable keys that provide access to its values. There is something called and OrderedDict which you may look at – joel goldstick Jul 08 '16 at 22:24
  • You can't. Check out http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value for a possible solution, or use an Ordered Dictionary – Nick Becker Jul 08 '16 at 22:24
  • A dictionary can have a sorted _string representation_, but it itself cannot be inherently sorted i.e. `for i in dictionary` doesn't guarantee any order. – Akshat Mahajan Jul 08 '16 at 22:25

2 Answers2

6

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'])])
>>> 
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

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.

Forhadul Islam
  • 1,159
  • 11
  • 13