Python:从字典中删除一个值并引发异常

时间:2013-06-01 01:31:07

标签: python dictionary

顺序无关紧要,除非所有值都为空,否则如何删除值? 它也引发了没有价值的异常

例如:

d = {'a':1,'b':2,'c':1,'d':3}
remove a : {'b':2,'c':1,'d':3}
remove b : {'b':1,'c':1,'d':3}  
remove b : {'c':1,'d':3}
remove c : {'d':3}
remove d : {'d':2}
remove d : {'d':1}
remove d : {}
ValueError: d.remove(a): not in d

3 个答案:

答案 0 :(得分:3)

d = {'a':1,'b':2,'c':1,'d':3}

while True:
    try:
        k = next(iter(d))
        d[k] -= 1
        if d[k] <= 0: del d[k]
        print d
    except StopIteration:
        raise ValueError, "d.remove(a): not in d"

{'c': 1, 'b': 2, 'd': 3}
{'b': 2, 'd': 3}
{'b': 1, 'd': 3}
{'d': 3}
{'d': 2}
{'d': 1}
{}

Traceback (most recent call last):
  File "/home/jamylak/weaedwas.py", line 10, in <module>
    raise ValueError, "d.remove(a): not in d"
ValueError: d.remove(a): not in d

答案 1 :(得分:0)

d = {'a':1,'b':2,'c':1,'d':3}
for key in list(d.keys()):
    while True:
        print(d)
        d[key] -= 1
        if not d[key]:
            d.pop(key)
            break
    if not d:
        raise ValueError('d.remove(a): not in d')

输出:

{'a': 1, 'c': 1, 'b': 2, 'd': 3}
{'c': 1, 'b': 2, 'd': 3}
{'b': 2, 'd': 3}
{'b': 1, 'd': 3}
{'d': 3}
{'d': 2}
{'d': 1}

ValueError: d.remove(a): not in d

答案 2 :(得分:-1)

简单:

d = {'a':1,'b':2,'c':1,'d':3}

# No exception is raised in this case, so no error handling is necessary.
for key in d:
    value = d.pop(key)
    # <do things with value>