我有两本字典,但为了简化起见,我就选这两本:
>>> x = dict(a=1, b=2)
>>> y = dict(a=2, b=2)
现在,我想比较x中的每个键值对在y中是否有相同的对应值,所以我这样写:
>>> for x_values, y_values in zip(x.iteritems(), y.iteritems()):
if x_values == y_values:
print 'Ok', x_values, y_values
else:
print 'Not', x_values, y_values
它的工作原理是返回一个元组,然后比较是否相等。
我的问题:
这对吗?还有更好的办法吗?最好不是在速度上,我说的是代码优雅。
更新:我忘了提到,我必须检查有多少键,值对是相等的。
测试两个字典的键和值是否相等:
def dicts_equal(d1,d2):
""" return True if all keys and values are the same """
return all(k in d2 and d1[k] == d2[k]
for k in d1) \
and all(k in d1 and d1[k] == d2[k]
for k in d2)
如果你想返回不同的值,请以不同的方式书写:
def dict1_minus_d2(d1, d2):
""" return the subset of d1 where the keys don't exist in d2 or
the values in d2 are different, as a dict """
return {k,v for k,v in d1.items() if k in d2 and v == d2[k]}
你必须调用它两次,即
dict1_minus_d2(d1,d2).extend(dict1_minus_d2(d2,d1))
我有一个默认/模板字典,我想从第二个给定的字典更新它的值。因此,更新将发生在默认字典中存在的键以及相关值与默认键/值类型兼容的键上。
在某种程度上,这与上面的问题类似。
我写下了这个解:
CODE
def compDict(gDict, dDict):
gDictKeys = list(gDict.keys())
for gDictKey in gDictKeys:
try:
dDict[gDictKey]
except KeyError:
# Do the operation you wanted to do for "key not present in dict".
print(f'\nkey \'{gDictKey}\' does not exist! Dictionary key/value no set !!!\n')
else:
# check on type
if type(gDict[gDictKey]) == type(dDict[gDictKey]):
if type(dDict[gDictKey])==dict:
compDict(gDict[gDictKey],dDict[gDictKey])
else:
dDict[gDictKey] = gDict[gDictKey]
print('\n',dDict, 'update successful !!!\n')
else:
print(f'\nValue \'{gDict[gDictKey]}\' for \'{gDictKey}\' not a compatible data type !!!\n')
# default dictionary
dDict = {'A':str(),
'B':{'Ba':int(),'Bb':float()},
'C':list(),
}
# given dictionary
gDict = {'A':1234, 'a':'addio', 'C':['HELLO'], 'B':{'Ba':3,'Bb':'wrong'}}
compDict(gDict, dDict)
print('Updated default dictionry: ',dDict)
输出
“A”的值“1234”不是兼容的数据类型!!
键“a”不存在!字典键/值没有设置!!
{A: ", " B ":{“Ba”:0,“Bb”:0.0},“C”:['你好']}更新成功! !
{'Ba': 3, 'Bb': 0.0}更新成功!!
“Bb”的值“错误”不是兼容的数据类型!!
更新默认dictionry: {A:“B:{“Ba”:3,“Bb”:0.0},“C”:['你好']}
参见字典视图对象:
https://docs.python.org/2/library/stdtypes.html#dict
这样你可以从dictView1中减去dictView2,它将返回一组在dictView2中不同的键/值对:
original = {'one':1,'two':2,'ACTION':'ADD'}
originalView=original.viewitems()
updatedDict = {'one':1,'two':2,'ACTION':'REPLACE'}
updatedDictView=updatedDict.viewitems()
delta=original | updatedDict
print delta
>>set([('ACTION', 'REPLACE')])
你可以交叉,并,差(如上所示),对称差这些字典视图对象。
更好吗?更快呢?-不确定,但它是标准库的一部分-这使得它在可移植性方面有很大的优势
迟回复总比不回复好!
比较Not_Equal比比较Equal更有效。因此,如果一个字典中的任何键值在另一个字典中找不到,那么两个字典就不相等。下面的代码考虑到您可能会比较默认的dict,因此使用get而不是getitem[]。
在get调用中使用一种随机值作为默认值,等于要检索的键-以防dicts在一个dict中有None作为值,而该键在另一个dict中不存在。此外,为了提高效率,get !=条件是在not in条件之前检查的,因为您同时对两边的键和值进行检查。
def Dicts_Not_Equal(first,second):
""" return True if both do not have same length or if any keys and values are not the same """
if len(first) == len(second):
for k in first:
if first.get(k) != second.get(k,k) or k not in second: return (True)
for k in second:
if first.get(k,k) != second.get(k) or k not in first: return (True)
return (False)
return (True)