Home > Blockchain >  Dictionary difference similar to set difference
Dictionary difference similar to set difference

Time:04-29

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?

CodePudding user response:

One way could be to use dict.pop in loop:

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}

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related