0

Consider a dict of the following form:

dic = { "First": { 3: "Three" }, "Second": { 1: "One" }, "Third": { 2:"Two" } } 

I would like to sort it by the nested dic key (3, 1, 2)

I tried using the lambda function in the following manner but it returns a "KeyError: 0"

dic = sorted(dic.items(), key=lambda x: x[1][0])

The expected output would be:

{ "Second": { 1: "One" }, "Third": { 2: "Two" }, "First": { 3:"Three" } } 

In essence what I want to know is how to designate a nested key independently from the main dictionary key.

4
  • 3
    Dictionaries can't be sorted. Commented Jul 9, 2019 at 19:55
  • What would the expected output be if the nested dicts contained more than one key each? For example, {"first": {3: "three", 1:"one"}, "second": {2:"two"}}? Commented Jul 9, 2019 at 19:56
  • Do you mean you want to sort the dictionary's nested keys, then iterate over / use those keys? Commented Jul 9, 2019 at 19:56
  • @ScottHunter, As of Python 3.7, dictionaries are ordered, so in principle they can be sorted. Now as for whether it's a good idea to sort them, is another question entirely... Commented Jul 9, 2019 at 20:05

2 Answers 2

5

In the lambda function, x is a key-value pair, x[1] is the value, which is itself a dictionary. x[1].keys() is its keys, but it needs to be turned into a list if you want to get its one and only item by its index. Thus:

sorted(dic.items(), key = lambda x: list(x[1].keys())[0]) 

which evaluates to:

[('Second', {1: 'One'}), ('Third', {2: 'Two'}), ('First', {3: 'Three'})] 
Sign up to request clarification or add additional context in comments.

Comments

0
dic = {'First': {3: 'Three'}, 'Second': {1: 'One'}, 'Third': {2: 'Two'}} sorted_list = sorted(dic.items(), key=lambda x:list(x[1].keys())[0]) sorted_dict = dict(sorted_list) print(sorted_dict) 

You need to get the keys for the nested dictionary first and then convert them into list and sort over its first index. You will get a sorted list. All you need to convert this list to dictionary using dict(). I hope that helps. This snippet works for python3.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.