Ciprian
Ciprian

Reputation: 279

Remove dictionary from another dictionary (strange behavior in python 3)

I have two dict

runde = {
    "A": ["1, 2, 3", "4, 5, 6"],
    "B": ["1, 2, 3", "4, 5, 6"],
    "C": ["1, 2, 3", "4, 5, 6"],
    "D": ["1, 2, 3", "4, 5, 6"],
}

bilete = {
    "B": ["1, 2, 3", "4, 5, 6"],
    "C": ["1, 2, 3", "4, 5, 6"],
}

I want to substract bilete from runde, with result

runde = {
    "A": ["1, 2, 3", "4, 5, 6"],
    "B": [],
    "C": [],
    "D": ["1, 2, 3", "4, 5, 6"],
}

The code

for key in runde:
    if key in bilete:
        b = bilete[key]
        for a in b:
            runde[key].remove(a)

This code works fine, but in my situation, after first .remove, the result is

{'A': ['4, 5, 6'],'B': ['4, 5, 6'],'C': ['4, 5, 6'],'D': ['4, 5, 6']}

after second .remove the result is

{'A': [],'B': [],'C': [],'D': []}

and then I get the error ValueError: list.remove(x): x not in list

This is my situation, any help would be greatly appreciated:

import pickle
# here is my variables saved: import.pkl
# https://drive.google.com/file/d/1SbJm9J5dFQgc1H6m8C6epqDLAs2m15lS/view?usp=sharing
with open('import.pkl', 'rb') as f:
    runde, bilete = pickle.load(f)
for key in runde:
    if key in bilete:
        b = bilete[key]
        for a in b:
            runde[key].remove(a)

Upvotes: 0

Views: 65

Answers (2)

quamrana
quamrana

Reputation: 39374

If I type in this code:

runde = {
    "A": ["1, 2, 3", "4, 5, 6"],
    "B": ["1, 2, 3", "4, 5, 6"],
    "C": ["1, 2, 3", "4, 5, 6"],
    "D": ["1, 2, 3", "4, 5, 6"],
}

bilete = {
    "B": ["1, 2, 3", "4, 5, 6"],
    "C": ["1, 2, 3", "4, 5, 6"],
}

for key in runde:
    if key in bilete:
        b = bilete[key]
        for a in b:
            runde[key].remove(a)

print(runde)

I get this output:

{'A': ['1, 2, 3', '4, 5, 6'], 'B': [], 'C': [], 'D': ['1, 2, 3', '4, 5, 6']}

I'm trying to guess exactly what data you have, but so far I haven't been able to reproduce your exact symptoms.

If, however, I type in this code:

first = "1, 2, 3"
second = "4, 5, 6"
coll = [first, second]
runde = {
    "A": coll,
    "B": coll,
    "C": coll,
    "D": coll,
}

bilete = {
    "B": coll,
    "C": coll,
}

for key in runde:
    if key in bilete:
        b = bilete[key]
        for a in b:
            runde[key].remove(a)
            print(runde)

print(runde)

I get this output:

{'A': [], 'B': [], 'C': [], 'D': []}

and no error.

Also, if I insert this code before all the loops:

import copy
for k in runde:
    runde[k] = copy.deepcopy(runde[k])

then the output returns to the desired output.

Upvotes: 2

Rajnish kumar
Rajnish kumar

Reputation: 196

Looks like you are getting different dictionaries while reading

with open('import.pkl', 'rb') as f:
runde, bilete = pickle.load(f)

The code you have posted, should return correct result.

Upvotes: 0

Related Questions