Answer the question
In order to leave comments, you need to log in
How to sort and display such dictionary A = {"A_1": {1: "Yes"}, "C_2":{2: "No"}, "B_1": {1: "Yes"}}?
I need to sort the dictionary like this:
{"A_1": {1 : "Yes"}, "B_1": {1 : "Yes"} , "C_2":{2 : "No"}}
or here is the second example:
{"A_2":{2:"Yes"}, "B_1":{1:"No"}} --> {"B_1":{1:"No"}, "A_2":{2:"Yes "}}
That is, I need to sort by the key of the value (more precisely, in a dictionary in one entry, I have a value in which there is another dictionary and I need to sort by the key of the second dictionary)
And I need to display the dictionary so that it looks something like this:
A_1 - Yes
B_1 - Yes
C_2 - No
or
B_1 - No
A_2 - Yes
Answer the question
In order to leave comments, you need to log in
def get_nested_key(data):
return list(data[1])
dict(sorted(your_dict.items(), key=get_nested_key))
Dictionaries, by definition, are not sorted. More precisely, they do not guarantee the preservation of sorting (although it seems to be preserved in the latest versions of Python, but this is a feature, I would not rely on it yet).
Also, there is a special collections.OrderedDict, but it requires collections to be imported.
But you can turn your dictionary into a list of lists [key, value] and sort it by the second element. And bring him out. If there are nested dictionaries, then you need to do this business recursively. I hope you have already figured out the recursion?
This is how the list output works:
a = {"A_2":{2:""}, "B_1":{1:"No"}, "A_3":{3:"Yes"}}
a = {key: a.get(key) for key in sorted(a, key=lambda x: [(int(i[1]), i[0]) for i in [x.split('_')]][0])}
for k, v in a.items():
l = []
l.append(str(v.values()))
if len(''.join(l)[14:len(str(v.values())) - 3]) > 0:
print(f"{k} - {''.join(l)[14:len(str(v.values())) - 3]}")
else:
print(f"{k} - Ничего не записанно")
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question