从另一个字典中删除字典(python 3中的奇怪行为)

2024-09-30 00:38:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两本字典

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

我想从runde中减去bilete,得到结果

runde = {
    "A": ["1, 2, 3", "4, 5, 6"],
    "B": [],
    "C": [],
    "D": ["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)

这段代码运行良好,但在我的情况下,在first.remove之后,结果是

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

第二次之后。移除结果为

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

然后我得到错误值error:list.remove(x):x不在列表中

这是我的情况,任何帮助都将不胜感激:

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)

Tags: key代码inimportforif字典情况
2条回答

如果我键入此代码:

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)

我得到这个输出:

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

我正试图猜测你到底有什么数据,但到目前为止,我还无法重现你的确切症状

但是,如果我键入此代码:

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)

我得到这个输出:

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

没有错误

此外,如果在所有循环之前插入此代码:

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

然后,输出返回到所需的输出

看起来您在阅读时会收到不同的词典

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

您发布的代码应返回正确的结果

相关问题 更多 >

    热门问题