[英]remove items from 2 dictionaries python 3
我有以下字典:
a = {'f': 2, 'u': 210, 'the': 100, 'too': 300, 'my': 199, 'is': 2466, 'and': 3787}
b = {'f': 9, 'u': 17, 'o': 14, 'the': 23, 'yy': 7, 'and': 12}
我想從兩個字典中刪除類似的鍵。
我有以下代碼:
for item in a:
if item in b.keys():
del a[item]
該代碼類似於修改字典b。
運行它時,出現以下錯誤:
Traceback (most recent call last):
File "None", line 4, in <module>
builtins.RuntimeError: dictionary changed size during iteration
有沒有解決方法,而無需使用Deepcopy,dict.has_key,zip或任何模塊? 同樣,字典可以是任意長度。
是的,您可以遍歷list(dict)
。 這將返回鍵列表。 在Python2中,您還可以使用dict.keys()
。
for item in list(a):
if item in b: #Don't use b.keys() here, it is slow.
del a[item]
您可以使用字典理解 :
>>> a = {'f': 2, 'u': 210, 'the': 100, 'too': 300, 'my': 199, 'is': 2466, 'and': 3787}
>>> b = {'f': 9, 'u': 17, 'o': 14, 'the': 23, 'yy': 7, 'and': 12}
>>> a = {k:v for k,v in a.items() if k not in b}
>>> a
{'is': 2466, 'my': 199, 'too': 300}
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.