2015-03-08 147 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]}