How to sort keys in multidimensional dict
Question:
I have multidimensional dict:
my_dict = {
"first": {
"bbb": "aaa",
"ccc": "sdfs",
"aaa": "123"
},
"other": {
"ttt": "a",
"e": "e",
"yy": "y"
},
"aaa": {
"q": "a",
"e": "e",
"r": "y"
}
}
I would like to sort the second dimension in this dictionary based on the keys alphabetically.
I would like to receive:
my_new_dict = {
"first": {
"aaa": "123",
"bbb": "aaa",
"ccc": "sdfs"
},
"other": {
"e": "e",
"ttt": "a",
"yy": "y"
},
"aaa": {
"e": "e",
"q": "a",
"r": "y"
}
}
I have tried:
my_new_dict = sorted(my_dict.items(), key=lambda x: lambda y: y[0])
but this return me error:
TypeError: ‘<‘ not supported between instances of ‘dict’ and ‘dict’.
Answers:
You can use sorted
for each of the sub-dictionaries:
my_dict = { "first": { "bbb": "aaa", "ccc": "sdfs", "aaa": "123" }, "other": { "ttt": "a", "e": "e", "yy": "y" }, "aaa": { "q": "a", "e": "e", "r": "y" } }
output = {k: dict(sorted(v.items())) for k, v in my_dict.items()}
print(output)
# {'first': {'aaa': '123', 'bbb': 'aaa', 'ccc': 'sdfs'},
# 'other': {'e': 'e', 'ttt': 'a', 'yy': 'y'},
# 'aaa': {'e': 'e', 'q': 'a', 'r': 'y'}}
Note that "sorting" of a dict is guaranteed to work only for python 3.7+.
I have multidimensional dict:
my_dict = {
"first": {
"bbb": "aaa",
"ccc": "sdfs",
"aaa": "123"
},
"other": {
"ttt": "a",
"e": "e",
"yy": "y"
},
"aaa": {
"q": "a",
"e": "e",
"r": "y"
}
}
I would like to sort the second dimension in this dictionary based on the keys alphabetically.
I would like to receive:
my_new_dict = {
"first": {
"aaa": "123",
"bbb": "aaa",
"ccc": "sdfs"
},
"other": {
"e": "e",
"ttt": "a",
"yy": "y"
},
"aaa": {
"e": "e",
"q": "a",
"r": "y"
}
}
I have tried:
my_new_dict = sorted(my_dict.items(), key=lambda x: lambda y: y[0])
but this return me error:
TypeError: ‘<‘ not supported between instances of ‘dict’ and ‘dict’.
You can use sorted
for each of the sub-dictionaries:
my_dict = { "first": { "bbb": "aaa", "ccc": "sdfs", "aaa": "123" }, "other": { "ttt": "a", "e": "e", "yy": "y" }, "aaa": { "q": "a", "e": "e", "r": "y" } }
output = {k: dict(sorted(v.items())) for k, v in my_dict.items()}
print(output)
# {'first': {'aaa': '123', 'bbb': 'aaa', 'ccc': 'sdfs'},
# 'other': {'e': 'e', 'ttt': 'a', 'yy': 'y'},
# 'aaa': {'e': 'e', 'q': 'a', 'r': 'y'}}
Note that "sorting" of a dict is guaranteed to work only for python 3.7+.