Inherited Geek
Inherited Geek

Reputation: 2383

Sort Python Dictionary Objects in a List

I am trying to sort the List using dictionary keys in ascending order.

You can assume just one key per dictionary level.

Input:

res = [{'hi': {'abc': 5}}, {'bye': {'def': 5}}, {'hi': {'cba': 5}}]

My Code:

def getitem (item):
    return (item.keys())

print (sorted(res, key = getitem))

Required Output:

[{'bye': {'def': 5}}, {'hi': {'abc': 5}}, {'hi': {'cba': 5}}]

Upvotes: 1

Views: 52

Answers (1)

ggorlen
ggorlen

Reputation: 56875

You're close--just pass the dict into iter() to create an iterator, then ask for the next() item in the iterator. This sorts on the first key in the dict if multiple exist (Python 3.6+ dicts are ordered by insertion time). The comparator can return a tuple of relative priority, enabling sorting on the inner key if the outer keys are equal.

res = [{'hi': {'abc': 5}}, {'bye': {'def': 5}}, {'hi': {'cba': 5}}]

def compare(d):
    outer = next(iter(d))
    return outer, next(iter(d[outer]))

print(sorted(res, key=compare))

Upvotes: 2

Related Questions