python - 如何比较 2 个有序字典并创建一个新的有差异的有序字典? ( python 3.7)

标签 python comparison ordereddictionary array-difference

我正在努力研究如何生成一个“差异”有序字典,其中包含比较后出现在“修改的”有序字典上的不同值和新值带有“引用”有序字典

示例:

#python

from collections import OrderedDict

ref_d = OrderedDict() # REFERENCE Ordered Dictionary
mod_d = OrderedDict() # MODIFIED Ordered Dictionary
dif_d = OrderedDict() # DIFFERENCES Ordered Dictionary (what I'm looking for)

# This is my REFERENCE ordered dictionary with default values

ref_d = {
    'shape': 'square',
    'color': 'white',
    'posxy': '0,0',
    'scale': 'small',
    'rotxy': '0,0',
    'modif': 'no',
    'autom': 'no',
    'lumin': 'min',
    'backg': 'none',
    'outpu': 'no'
}

# This is my MODIFIED ordered dictionary, with some different values, and even some NEW key/value pairs

mod_d = {
    'shape': 'square',
    'color': 'red', # Different <-
    'posxy': '0,0',
    'scale': 'small',
    'rotxy': '0.5,0.5', # Different <-
    'modif': 'no',
    'autom': 'no',
    'varia': 'true', # NEW <-
    'lumin': 'max',
    'backg': 'none',
    'outpu': 'yes', # Different <-
    'specm': 'true' # NEW <-
}

# THIS IS WHAT I NEED: a "DIFFERENCES ordered dictionary", where different values and NEW key/values are added in same order

dif_d = {
    'color': 'red', # Different <-
    'rotxy': '0.5,0.5', # Different <-
    'varia': 'true', # NEW <-
    'outpu': 'yes', # Different <-
    'specm': 'true', # NEW <-
}

使用:

set0 = set(ref_d.items())
set1 = set(mod_d.items())
dif_d = (set1 - set0)

我得到了一个有效的结果,除了它是完全未排序的:-(

我想它可能是这样的(使用肮脏的无效代码):

for key, value in mod_d.items():
    if key, value != or not in ref_d: # Consider this as 'pseudo-code', it obviously fails...
        dif_d.update({key: value})

但我经常收到无效代码错误... 欢迎任何帮助! 谢谢!

最佳答案

您不能同时进行两个比较。您需要两个单独的检查:

for key, value in mod_d.items():
    if key not in ref_d:
        dif_d.update({key: value})
    else:
        if value != ref_d[key]:
            dif_d.update({key: value})

关于python - 如何比较 2 个有序字典并创建一个新的有差异的有序字典? ( python 3.7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74360336/

相关文章:

python - 我怎样才能获得List.__gt__()函数的源实现

r - 比较R中同一列中的两个变量

python OrderedDict 获取关键索引的

python - 如何使用dictionary/json在yaml中添加 '-'?

Python:测试的约定名称

python - 扩展特定版本的 Python(在 Linux Ubuntu/Unity 上)

python - pytest中fixture和yield_fixture的区别

string - python - 将字符串与 bool 值进行比较

python - Python-Requests 是否支持 OrderedDicts,还是这里出了其他问题?

python - 如何将 Pandas 饼图保存到文件中?