data = {'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5'}
keys = ('one', 'four')
unwanted = set(keys) - set(data)
for unwanted_key in unwanted: del data[unwanted_key]
我想要的输出是:
data = {'two': '2', 'three': '3', 'five': '5'}
我做错了什么?
我正在使用此接受answer的代码。
答案 0 :(得分:5)
我不确定你为什么需要这一行:
unwanted = set(keys) - set(data)
相反,只需直接定义unwanted
键:
>>> data = {'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5'}
>>> unwanted = ('one', 'four')
>>> for key in unwanted:
... del data[key]
...
>>> data
{'three': '3', 'five': '5', 'two': '2'}
答案 1 :(得分:1)
操作set(keys) - set(data)
将返回一个空集,因为它返回两组的差异
但你需要的是这两组set(keys) & set(data)
以下是适用于您的内容:
>>> data = dict(one=1, two=2, three=3, four=4, five=5)
>>> keys = ('one', 'four')
>>> set(data)
{'four', 'one', 'five', 'three', 'two'}
>>> set(keys)
{'four', 'one'}
>>> ukeys = set(data) & set(keys)
>>> ukeys
{'four', 'one'}
>>> for uk in ukeys: del data[uk]
...
>>>
>>> data
{'five': 5, 'three': 3, 'two': 2}