简体   繁体   中英

Python: remove a value from dictionary and raise exception

The order doesn't matter, how do you remove a value until all the values are empty? It also raise exception with no value existed

For example:

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
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
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')

Ouput:

{'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

Simple:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM