根据列表迭代中的值删除字典项

时间:2017-11-14 18:19:20

标签: python

我尝试了以下内容:

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:list indices必须是整数或切片,而不是str

我想迭代失败者并删除candidates_and_fp_votes中有losers

键的所有项目

我希望输出:

{'a': 24, 'c': 17, 'd': 23}

我该如何解决这个问题?

提前致谢。

4 个答案:

答案 0 :(得分:2)

i是列表元素,而不是索引。它应该是:

del candidates_and_fp_votes[i]

或它应该是:

for i in in range(len(losers)):

如果您出于某种原因真的想要索引。

答案 1 :(得分:1)

当您迭代一个对象(在本例中是一个名为'losers'的列表)时,变量i实际上是对象中的数据而不是您可能在其他语言中看到的数据索引(c / C ++)。因此,在for循环i == 'e'的第一次迭代中,然后是第二次i == 'b',然后循环将结束,因为没有更多数据。

所以你需要做的就是将输家[i]改为i:

del candidates_and_fp_votes[i]

以下是修复该行的完整代码。

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[i]
print(candidates_and_fp_votes)

答案 2 :(得分:1)

您的索引i是一个字符串,而不是整数。 你可以这样做:

losers = ['e', 'b']

candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

for i in losers:

     if i in candidates_and_fp_votes:
          del candidates_and_fp_votes[i]

print(candidates_and_fp_votes)

答案 3 :(得分:1)

您可以使用词典理解:

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}
相关问题