[英]Python 2.7.9 dictionary find and delete
Python 2.7.9 dictionary question: I have a dictionary in Python that contain lists that have been appended previously, and these lists are mapped, eg 1=>10.2, 2=>10.33 How may I find a single value within the dictionary and delete it? Python 2.7.9字典问题:我在Python中有一个字典,其中包含先前已附加的列表,并且这些列表已映射,例如1 => 10.2、2 => 10.33如何在字典中查找单个值并删除它? Eg find 'a'=2 and delete 'a' and corresponding 'b' value:
例如找到'a'= 2并删除'a'和相应的'b'值:
myDictBefore = {'a': [1, 2, 3], 'b': [10.2, 10.33, 10.05]}
myDictAfter = {'a': [1, 3], 'b': [10.2, 10.05]}
I suspect I should find 'a' value and get the index and then delete myDict['a'][index] 我怀疑我应该找到'a'值并获取索引,然后删除myDict ['a'] [index]
and myDict['b'][index] - though I'm unsure how to do this. 和myDict ['b'] [index]-尽管我不确定如何执行此操作。
How about: 怎么样:
idx = myDictBefore['a'].index(2)
myDictBefore['a'].pop(idx)
myDictBefore['b'].pop(idx)
If this comes up more often, you might as well write a general function for it: 如果出现这种情况的频率更高,则最好为它编写一个通用函数:
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)
which you could then use like this: 然后可以这样使用:
removeRow(myDictBefore, 'a', 2)
You could define a function that does it. 您可以定义一个执行此功能的函数。
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]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.