sara jones
sara jones

Reputation: 145

sort list of dictionaries based on keys inside the list

How can I sort this based on the key in dictionary?

df1 = [('f', {'abe': 1}), ('f', {'tbeli': 1}), ('f', {'mos': 1}), ('f', {'esc': 1})]

I tried this

L1 = [year for (title, year) in (sorted(df1.items(), key=lambda t: t[0]))]

I want

df1 = [('f', {'abe': 1}), ('f', {'esc': 1}), ('f', {'mos': 1}), ('f', {'tbeli': 1})]

Thanks

Upvotes: 0

Views: 52

Answers (2)

Tatts123
Tatts123

Reputation: 97

If all the dicts are going to be only 1 key/pair long then this should work.

L1=sorted(df1, key=lambda t: list(t[1].keys())[0])

Upvotes: 0

Ry-
Ry-

Reputation: 225271

You could have a separate function to get the only item in an iterable:

def only(iterable):
    x, = iterable
    return x

Dicts are iterables of keys:

>>> only({'abe': 1})
'abe'

>>> only({'tbeli': 1})
'tbeli'

so you can use it for your sort:

sorted(df1, key=lambda t: only(t[1]))

Upvotes: 2

Related Questions