'Dictionary difference similar to set difference

I have a dictionary and a list:

dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
remove = ['b', 'c', 'e']

I need to split "dictionary" into two dictionaries using "remove". The idea is to remove keys in "remove" from "dictionary" but instead of discarding them, I want to keep them in a new dictionary. The outcome I want is

old_dictionary = {'a':1, 'd':4, 'f':6}
new_dictionary = {'b':2, 'c':3, 'e':5}

Getting "new_dictionary" is fairly easy.

new_dictionary = {}
for key, value in dictionary.items():
    if key in remove:
        new_dictionary[key] = value

How do I find the difference between "dictionary" and "new_dictionary" to get "old_dictionary"? I guess I could loop again only with not in remove... but is there a nice trick for dictionaries similar to set difference?



Solution 1:[1]

One way could be to use dict.pop in loop. dict.pop method removes the key and returns its value. So in each iteration, we remove a key in remove from dictionary and add this key along with its value to new_dict. At the end of the iteration, dictionary will have all keys in remove removed from it.

new_dict = {k: dictionary.pop(k) for k in remove}
old_dict = dictionary.copy()

Output:

>>> new_dict
{'b': 2, 'c': 3, 'e': 5}

>>> old_dict
{'a': 1, 'd': 4, 'f': 6}

Solution 2:[2]

Just add else

new_dictionary = {}
old_dictionary = {}
for key, value in dictionary.items():
    if key in remove:
        new_dictionary[key] = value
    else:
        old_dictionary[key] = value

Solution 3:[3]

Use else: to put it in the other dictionary.

new_dictionary = {}
old_dictionary = {}
for key, value in dictionary.items():
    if key in remove:
        new_dictionary[key] = value
    else:
        old_dictionary[key] = value

Solution 4:[4]

The dict.keys() or dict.items() can be operated like a set with other iterable sequences:

>>> dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
>>> remove = list('bce')
>>> new_dict = {key: dictionary[key] for key in remove}
>>> new_dict
{'b': 2, 'c': 3, 'e': 5}
>>> dict(dictionary.items() - new_dict.items())
{'d': 4, 'f': 6, 'a': 1}

However, in terms of performance, this method is not as good as the answer with the highest score.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Kraigolas
Solution 3 Barmar
Solution 4