gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:16:56 26 4
gpt4 key购买 nike

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

示例:

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com