使用Python删除与列表相比的字典键。

huangapple go评论64阅读模式
英文:

Remove the dictionary keys compare to list using python

问题

我正在尝试执行的实际操作是,我正在处理一个包含大量字典数据和变量的任务。我需要比较这些变量和字典,并移除与之相关的部分。例如:

我的变量是:("ken", "col", "PVS")

test_dict = {"Pant": 22, "Shirt": 21, "Col high": 21, "Ken-super": 21, "Ken": 82}

print("在执行移除之前的字典:\n" + str(test_dict))

a_dict = {key: test_dict[key] for key in test_dict if key != 'Ken'}

print("执行移除之后的字典:\n", a_dict)

如果我运行上述代码,它只会从 test_dict 中移除 ken。我需要移除那些包含在我的 words 变量中的单词,同时也需要移除与我的 words 变量相似的单词。比如,需要移除 Ken-supercol High

我期望的输出是:{'Pant': 22, 'Shirt': 21}。就是这样。我期望移除与我的字典相似的单词。

英文:

Actual what I'm trying to perform, I working to with big dictionary data and variables . I need to compare the variables and dict and remove the which as relate to same. Eg:-

My words = ("ken",col","PVS")



test_dict = {"Pant": 22, "Shirt": 21, "Col high": 21, "Ken-super": 21, "Ken": 82}

print("The dictionary before performing remove is : \n" + str(test_dict))

a_dict = {key: test_dict[key] for key in test_dict if key != 'Ken'}

print("The dictionary after performing remove is : \n", a_dict)


If i run above code it will remove only ken only from test_dict. I need to remove the words which as contain on my words variable and also i need to remove the similar to my words variable. Like need to remove Ken-super,col High too

I need output like
{'Pant': 22, 'Shirt' : 21} only.
That's it

My expecting the output of Remove the similar words which compare to my dict

答案1

得分: 2

这将帮助你获得你想要的结果。

bad_words = ("ken", "col", "PVS")
test_dict = {"Pant": 22, "Shirt": 21, "Col high": 21, "Ken-super": 21, "Ken": 82}
new_dict = {key: value for key, value in test_dict.items() if not any(word in key.lower() for word in bad_words)}
print(new_dict)
英文:

This should get you what you want.

bad_words = ("ken","col","PVS")
test_dict = {"Pant": 22, "Shirt": 21, "Col high": 21, "Ken-super": 21, "Ken": 82}
new_dict = {key: value for key, value in test_dict.items() if not any(word in key.lower() for word in bad_words)}
print(new_dict)

huangapple
  • 本文由 发表于 2023年1月6日 14:56:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75027861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定