def strictInsert( existingDict, key, value ):
# check to see if the key is present
if key in existingDict:
# assuming you only want an error if the new value is
# different from the old one...
if existingDict[key] != value:
# raise an error
raise ValueError( "Key '%s' already in dict"%key )
else:
# insert into the dict
existingDict[key] = value
temp = {'A': 3, 'S': 1}
strictInsert( temp, 'A', 4 )
这将产生:
Traceback (most recent call last):
File "so.py", line 15, in <module>
strictInsert( temp, 'A', 4 )
File "so.py", line 8, in strictInsert
raise ValueError( "Key '%s' already in dict"%key )
ValueError: Key 'A' already in dict
temp = {
'A': 3
'S' : 1
}
def insert_or_raise(k, v) {
global temp # assuming temp is global and accessible
val = temp.get(k, None)
if not val:
temp[k] = v
return
if v != val:
raise Error("values are not same , already inserted %s for key %s " % (val, k))
}
insert('B', 1) # inserts okay
insert('B', 1) # does nothing, same key, value pair exists
insert('B', 2) # raise Error value is not 1 for key B
if set(temp.keys()).intersection(set(other.keys())):
# report the error
如果可以有一个重复的键,只要它是相同的值,那么对上面的简单更改将为您提供:
if 'A' in temp and temp['A'] != 4:
# can't insert the new value 'A': 4
if [True for x in set(temp.keys()).intersection(set(other.keys())) if temp[x] != other[x]]:
# at least one value in temp doesn't match a value in other
这将产生:
找这样的东西?你知道吗
您可以测试字典中是否已存在密钥:
要合并两个词典,可以通过创建关键点集并确保交点为空来测试关键点是否重叠:
如果可以有一个重复的键,只要它是相同的值,那么对上面的简单更改将为您提供:
相关问题 更多 >
编程相关推荐