1

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}}]
6
  • 1
    Do you dictionaries always have one key? In which case, why ese a dictionary at all? The comparison operators for dict.keys objects are for subset relationship Commented Jun 21, 2019 at 18:05
  • Apologies for the confusion, I have updated the examples, there can be just one key in the dict, but there can be more than 1 objects with the same key and if the object key is same ("hi" in the above case), then I would like to sort it by it's nested key ("abc" before "cba"). Commented Jun 21, 2019 at 18:15
  • 2
    You should just be using tuples probably, why a nested dictionary? The tuples would sort naturally how you want them to, and be much more memory efficient Commented Jun 21, 2019 at 18:17
  • I am receiving these dictionary objects one by one from a streaming data source. Commented Jun 21, 2019 at 18:22
  • ... so is there something preventing you from transforming them into a more sane/useful data structure? Commented Jun 21, 2019 at 18:25

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

3 Comments

next(iter(x)) would be sufficient; no need to call the keys method.
Good call--thanks. I guess it'll ignore the nested dict?
It will; Python's sorting methods are stable, so if the two top-level keys are equal, the relative order of the dicts in the input list is preserved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.