Skip to content Skip to sidebar Skip to footer

Python How To Delete A Specific Value From A Dictionary Key With Multiple Values?

I have a dictionary with multiple values per key and each value has two elements (possibly more). I would like to iterate over each value-pair for each key and delete those values-

Solution 1:

The code like this:

myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}
for v in myDict.values():
    if ('Ok!', '0') in v:
        v.remove(('Ok!', '0'))
print(myDict)

Solution 2:

You can also do like this:

myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}
del myDict['A'][1]
print(myDict)

Explanation :

myDict['A'] - It will grab the Value w.r.t Key A

myDict['A'][1] - It will grab first index tuple

del myDict['A'][1] - now this will delete that tuple

Solution 3:

myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}
for v in myDict.values():
    for x in v:
        if x[0] == 'Ok!'and x[1] == '0':
            v.remove(x)
print(myDic)

Post a Comment for "Python How To Delete A Specific Value From A Dictionary Key With Multiple Values?"