我有两个字典,它们的顺序由它们的值表示。
d1= {570.44: 2, 305.21: 1, 271.94: 0, 463.20: 3, 556.60: 4, 596.27: 5}
d2= {570.44: 537.5, 596.27: 767.0, 556.60: 644.5, 271.94: 285.0, 305.21: 334.5, 463.20: 428.5}
我想比较顺序,这是由值定义的。
例如,570.44
根据值的不同而不会相同,在 d1 中它将位于第三个位置,而在 d2 中它将位于第四个位置。
d1[570.44] < d2[570.44]
如您所见,当我指的是顺序时,我的意思是由键的值确定的顺序,而不是由插入顺序等确定的顺序。
如何比较这两个词典? (通常比较是为了相等,如 question 但我对顺序感兴趣
最佳答案
如果我理解正确的话,这可能就是你想要的。只需按字典的值对字典进行排序并比较有序键的列表即可。
In [10]: d1_ordered = [k for k, _ in sorted(d1.items(), key=lambda x: x[1])]
In [11]: d2_ordered = [k for k, _ in sorted(d2.items(), key=lambda x: x[1])]
In [12]: d1_ordered
Out[12]: [271.94, 305.21, 570.44, 463.2, 556.6, 596.27]
In [13]: d2_ordered
Out[13]: [271.94, 305.21, 463.2, 570.44, 556.6, 596.27]
In [14]: for idx, d1_k in enumerate(d1_ordered):
...: if d1_k not in d2_ordered:
...: print(f"Key {d1_k} not exists in d2")
...: continue
...: if idx != d2_ordered.index(d1_k):
...: print(f"Key {d1_k} is in different order in these dicts")
...:
Key 570.44 is in different order in these dicts
Key 463.2 is in different order in these dicts
关于python - 比较字典的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69173647/