Merge a dict in Python using 1 dict as base

This question already has an answer here:

  • How to merge two dictionaries in a single expression? 48 answers

  • "Pythonicness" is a hard measure to assess, but here is my take on it:

    def merge_dicts(base_dict, other_dict):
        """ Merge two dicts
    
        Ensure that the base_dict remains as is and overwrite info from other_dict
        """
        if other_dict is None:
            return base_dict
        t = type(base_dict)
        if type(other_dict) != t:
            raise TypeError("Mismatching types: {} and {}."
                            .format(t, type(other_dict)))
        if not issubclass(t, dict):
            return other_dict
        return {k: merge_dicts(v, other_dict.get(k)) for k, v in base_dict.items()}
    

    Example:

    merge_dicts({"a":2, "b":{"b1": 5, "b2": 7}}, {"b": {"b1": 9}})
    >>> {'a': 2, 'b': {'b1': 9, 'b2': 7}}
    

    If you're using python 3.5 or later you can simply do:

    merged_dict = {**base_dict, **other_dict}
    

    In case you're using any prior version you can do it with the update method:

    merged_dict = {}
    merged_dict.update(base_dict)
    merged_dict.update(other_dict)
    

    For more information about it you can check The Idiomatic Way to Merge Dictionaries in Python


    You can use the dict.update method, along with a generator expression:

    base_dict.update((k, v) for k, v in other_dict.items() if k in base_dict)
    

    Explanation

    base_dict.update(other_dict) will overwrite the values in base_dict with those in other_dict . If a key exists in other_dict but not in base_dict , it will be added to base_dict , which is not what you want. Therefore, you need to test if each key in other_dict is in base_dict .

    dict.update can take an iterable as first parameter. If the latter contains 2-tuples (k, v) , then base_dict[k] will be set to v .

    Abstract from help(dict.update) :

    update(...) method of builtins.dict instance

    If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v

    Therefore, it's convenient to pass a generator expression to it. If you're not familiar with generator expressions, the stuff inside of the parentheses is more or less equivalent to the following:

    l = []
    for k, v in other.dict_items():
        if k in base_dict:
            l.append((k, v))
    

    Then l is passed to update , like base_dict.update(l) .

    链接地址: http://www.djcxy.com/p/17572.html

    上一篇: 线字典到单

    下一篇: 以1字典为基础合并Python中的字典