2015-03-08 146 views
0

Python 2.7.9字典問題: 我有一個Python中的字典,它包含之前附加過的列表,並且這些列表已被映射。 1 => 10.2,2 => 10.33 如何在字典中找到單個值並將其刪除? 例如找到「A」 = 2和刪除「a」和對應的「B」值:Python 2.7.9字典查詢和刪除

myDictBefore = {'a': [1, 2, 3], 'b': [10.2, 10.33, 10.05]} 

myDictAfter = {'a': [1, 3], 'b': [10.2, 10.05]} 

我懷疑應該找到「A」值,並得到索引,然後 刪除myDict [「一」] [指數]

和myDict ['b'] [index] - 雖然我不確定如何做到這一點。

回答

2

如何:

idx = myDictBefore['a'].index(2) 
myDictBefore['a'].pop(idx) 
myDictBefore['b'].pop(idx) 

如果這更經常出現,你不妨爲它編寫一個通用函數:

def removeRow(dct, col, val): 
    '''remove a "row" from a table-like dictionary containing lists, 
     where the value of that row in a given column is equal to some 
     value''' 
    idx = dct[col].index(val) 
    for key in dct: 
     dct[key].pop(idx) 

然後你可以使用這樣的:

removeRow(myDictBefore, 'a', 2) 
+0

L3viathan,非常感謝 - 是的,我失蹤了索引(x) - 非常感謝 – 2015-03-08 19:17:07

0

你可以定義一個函數來完成它。

def remove(d, x): 
    index = d['a'].index(x) # will raise ValueError if x is not in 'a' list 
    del d['a'][index] 
    del d['b'][index] 

myDict = {'a': [1, 2, 3], 'b': [10.2, 10.33, 10.05]} 

remove(myDict, 2) 
print(myDict) # --> {'a': [1, 3], 'b': [10.2, 10.05]}