当前位置: 动力学知识库 > 问答 > 编程问答 >

remove items from 2 dictionaries python 3

问题描述:

I have the following dictionaries:

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}

I want to remove similar keys from both dictionaries.

I have the following code:

 for item in a:

if item in b.keys():

del a[item]

The code is similar to modify dictionary b.

When I run it, I get the following error:

 Traceback (most recent call last):

File "None", line 4, in <module>

builtins.RuntimeError: dictionary changed size during iteration

Is there any way to solve this without using deepcopy, dict.has_key, zip or any modules? Also, the dictionaries can be of any length.

网友答案:

Yes, you can iterate over list(dict). This returns a list of keys. In Python2 you can also use dict.keys().

for item in list(a):
    if item in b:   #Don't use b.keys() here, it is slow.
        del a[item]
网友答案:

You can use a dictionary comprehension:

>>> 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}
>>>
分享给朋友:
您可能感兴趣的文章:
随机阅读: