I have a dictionary of dictionaries, that looks something like this:
"abc": {
"name": "Joey",
"order": 3
},
"def": {
"name": "Allen",
"order": 2
},
"ghi": {
"name": "Tim",
"order": 1
}
Now, I would like to sort this dictionary according to the "order" value.
Meaning, the sorted dictionary will look like:
"ghi": {
"name": "Tim",
"order": 1
}
"def": {
"name": "Allen",
"order": 2
},
"abc": {
"name": "Joey",
"order": 3
}
How can I do this? I found ways to sort a list of dictionaries, but not a dictionary of dictionaries.
Use sorted
to sort by "order" and collections.OrderedDict
to store the result,
import collections
d = {
"abc": {
"name": "Joey",
"order": 3
},
"def": {
"name": "Allen",
"order": 2
},
"ghi": {
"name": "Tim",
"order": 1
}
}
result = collections.OrderedDict(sorted(d.items(), key=lambda t:t[1]["order"]))
# Output
print(result)
OrderedDict([('ghi', {'name': 'Tim', 'order': 1}),
('def', {'name': 'Allen', 'order': 2}),
('abc', {'name': 'Joey', 'order': 3})])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With