[英]Remove values from dictionary based on key values
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]
The output that I want is: 我想要的输出是:
data = {'two': '2', 'three': '3', 'five': '5'}
What am I doing wrong? 我究竟做错了什么?
I am using the code of this accepted answer . 我正在使用此已接受答案的代码。
I'm not sure why you need this line: 我不确定为什么需要此行:
unwanted = set(keys) - set(data)
Instead, just define your unwanted
keys directly: 而是直接定义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'}
The operation set(keys) - set(data)
will return an empty set as it returns the difference of two sets but what you need is the intersection of those two sets set(keys) & set(data)
操作set(keys) - set(data)
将返回一个空集合,因为它返回两个集合的差,但是您需要的是这两个集合的交集set(keys) & set(data)
Here's what will work for you: 这将为您服务:
>>> 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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.