我尝试了以下方法:
losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
for i in losers:
del candidates_and_fp_votes[losers[i]]
print(candidates_and_fp_votes)
这只会返回错误:
TypeError:列表索引必须是整数或切片,而不是str
我想遍历失败者并删除
candidates_and_fp_votes
中具有losers
键的每个项目我期望输出:
{'a': 24, 'c': 17, 'd': 23}
我怎么解决这个问题?
提前致谢。
最佳答案
您可以使用字典理解:
losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
final_dict = {a:b for a, b in candidates_and_fp_votes.items() if a not in losers}
输出:
{'a': 24, 'c': 17, 'd': 23}