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-pairs that meet some criteria. Here for instance I would like to delete the second value pair for the key A; that is: ('Ok!', '0')
:
myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}
to:
myDict = {'A': [('Yes!', '8')], 'B': [('No!', '2')]}
I can iterate over the dictionary by key or value, but can't figure out how I delete a specific value.
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)
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 wrt Key A
myDict['A'][1] - It will grab first index tuple
del myDict['A'][1] - now this will delete that tuple
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.