Home > database >  Removing keys in pair form from dictionary
Removing keys in pair form from dictionary

Time:12-04

Suppose I have a python dictionary, tDosDict, like

{('M1', 'P1'): 6.0,
 ('M1', 'P2'): 10.0,
 ('M1', 'P3'): 4.0,
 ('M2', 'P1'): 7.0,
 ('M2', 'P2'): 6.0,
 ('M2', 'P3'): 5.0}

I am making some operations say,

valMin = min(tDosDict.values())
jobsR = [key for key in tDosDict if tDosDict[key] == valMin]

So I find that jobsR as ('M1', 'P3'). Now I would like to remove the all the keys where 'P3' appears from the tDosDict. So my updated keys will be

{('M1', 'P1'): 6.0,
 ('M1', 'P2'): 10.0,
 ('M2', 'P1'): 7.0,
 ('M2', 'P2'): 6.0,}

Again I shall make the same operation to drop the keys. I tried it in the following way, but it is not working

for key, value in tDosDict.items():
    if jobsR[0][1] in key[1]:
        tDosDict.pop(jobsR[0][1], None)
    

Kindly help me. Also I have to push it in the loop to iterate the process.

CodePudding user response:

The issue is that you cannot edit an iterable while iterating over it. To get around this I made a list of the keys to remove, then removed them in a separate loop:

tDosDict = {('M1', 'P1'): 6.0,
 ('M1', 'P2'): 10.0,
 ('M1', 'P3'): 4.0,
 ('M2', 'P1'): 7.0,
 ('M2', 'P2'): 6.0,
 ('M2', 'P3'): 5.0}
 
valMin = min(tDosDict.values())
jobsR = [key for key in tDosDict if tDosDict[key] == valMin]

remove_list = []
for key, value in tDosDict.items():
    if jobsR[0][1] in key[1]:
        remove_list.append(key)
for item in remove_list:
    tDosDict.pop(item)
    
print(tDosDict)

Output:

{('M1', 'P1'): 6.0, ('M1', 'P2'): 10.0, ('M2', 'P1'): 7.0, ('M2', 'P2'): 6.0}

CodePudding user response:

An iteration like the following would achieve what you need - no need to iterate twice:

d = {('M1', 'P1'): 6.0, ('M1', 'P2'): 10.0, ('M1', 'P3'): 4.0, ('M2', 'P1'): 7.0, ('M2', 'P2'): 6.0, ('M2', 'P3'): 5.0}

{x: y for x, y in d.items() if x[0] in ["M1", "M2"] and x[1] != "P3"}

OUTPUT

{('M1', 'P1'): 6.0, ('M1', 'P2'): 10.0, ('M2', 'P1'): 7.0, ('M2', 'P2'): 6.0}

CodePudding user response:

Don't remove from dict but directly create new dict with elements which you want to keep.

Use != instead of ==

tDosDict = {key:val for key, val in tDosDict.items() if val != valMin}

tDosDict = {
    ('M1', 'P1'): 6.0,
    ('M1', 'P2'): 10.0,
    ('M1', 'P3'): 4.0,
    ('M2', 'P1'): 7.0,
    ('M2', 'P2'): 6.0,
    ('M2', 'P3'): 5.0
}

valMin = min(tDosDict.values())
#jobsR = [key for key in tDosDict if tDosDict[key] == valMin]

tDosDict = {key:val for key, val in tDosDict.items() if val != valMin}

print(tDosDict)

CodePudding user response:

This will also give desired out put d={('M1', 'P1'): 6.0, ('M1', 'P2'): 10.0, ('M1', 'P3'): 4.0, ('M2', 'P1'): 7.0, ('M2', 'P2'): 6.0, ('M2', 'P3'): 5.0}

valMin = min(d.values()) jobsR = [key for key in d if d[key] == valMin]

for key in [key for key in d if key[1] ==jobsR[0][1] ]: del d[key]

print(d)

  • Related