python - 比较字典的顺序

标签 python numpy

我有两个字典,它们的顺序由它们的值表示。

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/

相关文章:

python - 获取两个 numpy 数组之间更改数据的索引

python - 如何将 N 添加到计数器的每个值? - Python

python - Django查询还从ForeignKey表返回数据

python - ipython并行和非复制发送numpy数组

Python-将列表中的字符串元素添加到数组中

python - Matplotlib xtick 给出 "The truth value of an array with more than one element is ambiguous"

python - matplotlib 以两种不同的方式打印图像

python - 在 python 中打开共享对象文件时出错(OSError : cannot open shared object file: No such file or directory)

向 Google 网站站长工具 API 发出的 PHP/Python 请求

python - Pandas根据Excel中的条件更改字体颜色并保存到相同的excel python