Harry Lime
Harry Lime

Reputation: 2217

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, e.g. 1=>10.2, 2=>10.33 How may I find a single value within the dictionary and delete it? E.g. find 'a'=2 and delete 'a' and corresponding 'b' value:

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]

and myDict['b'][index] - though I'm unsure how to do this.

Upvotes: 0

Views: 81

Answers (2)

martineau
martineau

Reputation: 123473

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]}

Upvotes: 0

L3viathan
L3viathan

Reputation: 27283

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)

Upvotes: 2

Related Questions