1

Firstly, Suppose I have a dictionary like given below:

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

Now if I encounter an item like 'A': 4 will it be added to the dictionary something like:

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

leaving behind the previously value of key A which was 3

Secondly, if my dictionary is

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

How can I report an error if the dictionary sees another item like 'A': 4 or 'S': 5

4

4 回答 4

2

您可以测试以查看字典中是否已存在键:

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
于 2012-07-26T22:34:20.517 回答
1

寻找这样的东西?

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
于 2012-07-26T22:35:50.493 回答
1
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
于 2012-07-26T22:38:56.870 回答
1

做到这一点的最好方法可能是子类化dict和覆盖__setitem__()以在密钥已经存在时引发异常。除非有人知道预先存在的一次性字典collections或其他东西......

class WriteOnceDict(dict):

    def __setitem__(self, key, value):
        try:
            retrieved_value = self[key]
        except KeyError:
            super(WriteOnceDict, self).__setitem__(key, value)
        if retrieved_value != value:
            raise KeyError('Different value already added for %s.' % key)

mydict = WriteOnceDict()
for key, value in input_data: #or appropriate code for whatever your input data is
    mydict[key] = value
于 2012-07-26T22:39:17.727 回答