0

I have a dictionary

 d = {('08', '10010'):6, ('23', '10017'):6,('06444', '10028'): 6,('21', '10027'): 6}

I want to sort it by the second value

If I have an item (x,y):z, I need it to be based on y

I did something like this but it doesn't work out

print sorted(d, key=lambda item:item[0][1])

any ideas ?

user3378649
  • 5,154
  • 14
  • 52
  • 76

2 Answers2

1

almost there...

sorted(d,key=lambda x: x[1])
[('08', '10010'), ('23', '10017'), ('21', '10027'), ('06444', '10028')]

note that this is the sorted list of the keys, not the dictionary. To get the full view of the dictionary (with values) change d to d.items()

karakfa
  • 66,216
  • 7
  • 41
  • 56
1

There's two problems:
1- To sort by second value of key-tuple, you forgot the .items() invocation

>>> print sorted(d.items(), key=lambda item:item[0][1])
[(('08', '10010'), 6), (('23', '10017'), 6), (('21', '10027'), 6), (('06444', '10028'), 6)]

2- If you need a dict where keys are sorted by that criteria, you need an OrderedDict object, because in a default dict keys' order is not guaranteed

>>> print dict( sorted(d.items(), key=lambda item:item[0][1]))
{('23', '10017'): 6, ('21', '10027'): 6, ('08', '10010'): 6, ('06444', '10028'): 6}
>>> from collections import OrderedDict
>>> print OrderedDict( sorted(d.items(), key=lambda item:item[0][1]))
OrderedDict([(('08', '10010'), 6), (('23', '10017'), 6), (('21', '10027'), 6), (('06444', '10028'), 6)])
xecgr
  • 5,095
  • 3
  • 19
  • 28