Andriy Shpuliar Andriy Shpuliar - 1 month ago 11
Python Question

Python: How to sort a list by given value in inner dictionary?

I have a list, which looks like this:

C = [
[129211, [{'cid': 142211, 'date': 1478550075, 'likes': {'count': 40}]
[128732, [{'cid': 142061, 'date': 1478550100, 'likes': {'count': 17}]
...
]


How to get a copy of this list sorted by values of 'count' in 'likes' (in this case it's 40 and 17)?

Answer

Simply use an appropriate sort key.

C = [
      [129211, [{'cid': 142211, 'date': 1478550075, 'likes': {'count': 40}}]],
      [128732, [{'cid': 142061, 'date': 1478550100, 'likes': {'count': 17}}]]
    ]
s = sorted(C, key=lambda i: i[1][0]['likes']['count'])

Note that your current list C is not properly structured - I've repaired the incorrect syntax.

Result:

>>> import pprint
>>> pprint.pprint(s)
[[128732, [{'cid': 142061, 'date': 1478550100, 'likes': {'count': 17}}]],
 [129211, [{'cid': 142211, 'date': 1478550075, 'likes': {'count': 40}}]]]