2013-06-01 51 views
-1

順序無關緊要,除非所有值都爲空,否則如何刪除值? 這也引發異常沒有價值存在Python:從字典中移除值並引發異常

例如:

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 

回答

-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> 
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 
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 
+0

問題詢問到刪除項目一次一個,將移除D'的''所有3'一次 – jamylak

+0

此外,這可以在while循環取代:'而d; d.popitem()'。但是@jamylak是正確的 – TerryA

+0

@jamylak每一步都會移除一個項目。沒有? –