Search code examples
pythonpython-3.5argument-unpacking

Merging two dic in python3 using Unpacking Generalisations in Python3.5


There are two dictionaries as follow which I want to merge them, my point is to select those keys that I am interested in, for example I am interested in all the keys except county. Solution I 've used is using del function after creating your new dictionary, however I am sure there are more ways that are more efficient to my solution. How can I solve this problem without del function using UNPACKING ARGUMENT.

    >>> d1 =  {'avgUserperDay': '12', 'avgPurchaseperDay': '1', 'country': 'Japan'}
    >>> d2 = {'tUser': 1, 'tPurchase': 0, 'country': 'Japan'}
    >>> d ={**d1,**d2}
    >>>{'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12', 'country': 'Japan'}
    >>> del d['country']
    >>> d
    {'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12'}

AFTER DISCUSSION,

This command works with 3.5.1,

>>> {**{k:v for k, v in chain(d1.items(), d2.items()) if k != 'country'}}
{'tUser': 1, 'tPurchase': 0, 'avgPurchaseperDay': '1', 'avgUserperDay': '12'}

Solution

  • If you don't want to use del, you can replace it by .pop(key). For example, using unpacking argument too:

    d = dict(d1, **d2)
    d.pop("country")
    

    Notice that .pop returns the value too (here "Japan").