How can I arrange a dictionary using python so that the values are represented from lowest to highest order?

huangapple go评论60阅读模式
英文:

How can I arrange a dictionary using python so that the values are represented from lowest to highest order?

问题

我有以下字典:

d = {'A': {'A1': 2, 'A4': 4, 'A5': 1}, 'B': {'B3': 1, 'B7': 8, 'B5': 2}}

如何重新排列字典以按值从低到高的顺序组织?
在重新排列字典基于值之后,我期望得到以下输出:

d = {'A': {'A5': 1, 'A1': 2, 'A4': 4}, 'B': {'B3': 1, 'B5': 2, 'B7': 8}}

我尝试使用排序选项 d = sorted(d.items()),但它基于键对字典进行排序。

英文:

I have the following dictionary:

d = {'A': {'A1': 2, 'A4': 4, 'A5': 1}, 'B': {'B3': 1, 'B7': 8, 'B5': 2}}

How can I rearrange the dictionary to organize the values from lowest to highest order?
I am expecting to have the following output after rearranging the dictionary based on the values:

d = {'A': {'A5': 1, 'A1': 2, 'A4': 4}, 'B': {'B3': 1, 'B5': 2, 'B7': 8,}}

I tried to use the sorted option, d = sorted(d.items()), but it sorts the dictionary based on the keys.

答案1

得分: 1

d = {'A': {'A1': 2, 'A4': 4, 'A5': 1}, 'B': {'B3': 1, 'B7': 8, 'B5': 2}}
sorted_dict = {i: dict(sorted(d[i].items(), key=lambda x: x[1])) for i in d.keys()}

Output:

{'A': {'A5': 1, 'A1': 2, 'A4': 4}, 'B': {'B3': 1, 'B5': 2, 'B7': 8}}
英文:
d = {'A': {'A1': 2, 'A4': 4, 'A5': 1}, 'B': {'B3': 1, 'B7': 8, 'B5': 2}}
sorted_dict = {i:dict(sorted(d[i].items(),key=lambda x:x[1])) for i in d.keys()}

I know that it's pretty hard to read, so I will try to explain what I can.
Basically, you are using the sorted function which takes an iterable and a function of one argument which tells the sorted function to sort the iterable on the basis of that lambda function.

Edit:
I forgot to show the output.

{'A': {'A5': 1, 'A1': 2, 'A4': 4}, 'B': {'B3': 1, 'B5': 2, 'B7': 8}}

答案2

得分: 0

你评论中的解决方案方向是正确的,你只需要使用循环对内部的dict进行排序,而不是外部的dict

d = {k: dict(sorted(v.items(), key=lambda x: x[1])) for k, v in d.items()}

之后,如果需要的话,你也可以对外部的字典进行排序。

d = dict(sorted(d.items()))

将所有操作合并到一个单一的字典推导式中。

d = {k: dict(sorted(v.items(), key=lambda x: x[1])) for k, v in sorted(d.items())}
英文:

The solution from your comment was on the right direction, you just need to sort the inner dicts with a loop and not the outer dict

d = {k: dict(sorted(v.items(), key=lambda x: x[1])) for k, v in d.items()}

after that you can also sort the outer dictionary if needed

d = dict(sorted(d.items()))

Everything in a single dict-comprehension

d = {k: dict(sorted(v.items(), key=lambda x: x[1])) for k, v in sorted(d.items())}

huangapple
  • 本文由 发表于 2023年6月6日 13:21:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76411623.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定