如果现有字典在python中看到另一项具有相同的键但值不同,如何报告错误

2024-04-20 06:20:11 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,假设我有一本字典,如下所示:

temp = {'A': 3, 'S': 1}

现在,如果我遇到一个类似'A': 4的条目,它会被添加到字典中吗

temp = {'A': 4, 'S': 1} 

留下键A以前的值3

其次,如果我的字典是

{'A': 3, 'S': 1} 

如果字典看到另一项,如'A': 4'S': 5,我如何报告错误


Tags: 字典报告错误条目temp
3条回答
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 'A' in temp:
    # report the error

要合并两个词典,可以通过创建关键点集并确保交点为空来测试关键点是否重叠:

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

相关问题 更多 >