I am pretty new to python and I have a doubt
I have a dict of dict which looks like
{"boy" : { "NN" : 3 ,"VB" : 3, "PP" : 2 } }
In case of a conflict of values as shown in the example above , I want to sort the internal dict based on their keys in descending order. The answer should look like :
{"boy" : {"VB" : 3, "NN" : 3, "PP":2} }
How can I do that ?
Use an OrderedDict
.
from collections import OrderedDict
outer_dict = {"boy" : { "NN" : 3 ,"VB" : 3, "AA" : 2 } }
for key in outer_dict:
inner_dict = outer_dict[key]
outer_dict[key] = OrderedDict(sorted(inner_dict.items(), reverse=True))
You could sort the inner dictionaries like this:
from collections import OrderedDict
dict_of_dict = {"boy" : { "NN" : 3 ,"VB" : 3, "AA" : 2 } }
# sort inner dictionaries by descending key values
dict_of_dict = {key: OrderedDict(sorted(inner_dict.items(), reverse=True))
for key, inner_dict in dict_of_dict.items()}
print(dict_of_dict) # -> {'boy': OrderedDict([('VB', 3), ('NN', 3), ('AA', 2)])}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.