Daniel Julian
Daniel Julian

Reputation: 117

Python sort list of dicts with lists inside

I have the following list structure:

[
    {'key1': 'value1', 
     'key2': [['mike', 'simmons', '54:17:47']], 
     'key3': 19390},
    {'key1': 'value1', 
     'key2': [['snart', 'simmons', '60:12:47']], 
     'key3': 19390}
]

I would like to sort this list by the second index of the key2 key ( I mean, by those 60:12:47 numbers)

I haven't found a standard way of doing this..

Thanks!

Upvotes: 2

Views: 71

Answers (2)

jpp
jpp

Reputation: 164843

Here is one way, assuming you want your values sorted as strings.

lst = [{'key1': 'value1', 'key2': [['snart', 'simmons', '60:12:47']], 'key3': 19390},
       {'key1': 'value1', 'key2': [['mike', 'simmons', '54:17:47']], 'key3': 19390}]

res = sorted(lst, key=lambda x: x['key2'][0][2])

# [{'key1': 'value1', 'key2': [['mike', 'simmons', '54:17:47']], 'key3': 19390},
#  {'key1': 'value1', 'key2': [['snart', 'simmons', '60:12:47']], 'key3': 19390}]

Upvotes: 6

Phydeaux
Phydeaux

Reputation: 2855

Use sorted with a comparator that uses that value:

sorted_list = sorted(my_list, key=lambda d: d['key2'][0][2])

Upvotes: 2

Related Questions