Oct-09-2019, 06:45 AM
Based upon available information on the internet, it seems that different dictionaries can be merged either by using double asterisk operator or by update method.
While the double asterisk method looks simplest and straight forward one liner, the update method can generally be deployed via a function, which in turn can be direct or one embedded in a class.
Prima-facie, double asterisk method looks most tempting. Experienced members are requested to advise whether this style could be adopted universally as the preferred one or whether there could be reasons to use update method instead.
For ready reference, sample code is placed below. Sample-1 covers double asterisk method while Sample-2 utilizes a straight function based upon update method.
Sample-3 has an update based function embedded in a class. This style facilitates the use of plus operator while merging the dictionaries, as seen from the last but one line (just before the print statement).
While the double asterisk method looks simplest and straight forward one liner, the update method can generally be deployed via a function, which in turn can be direct or one embedded in a class.
Prima-facie, double asterisk method looks most tempting. Experienced members are requested to advise whether this style could be adopted universally as the preferred one or whether there could be reasons to use update method instead.
For ready reference, sample code is placed below. Sample-1 covers double asterisk method while Sample-2 utilizes a straight function based upon update method.
Sample-3 has an update based function embedded in a class. This style facilitates the use of plus operator while merging the dictionaries, as seen from the last but one line (just before the print statement).
# Merging Dictionaries: Different Styles a = {'de': 'Germany'} b = {'sk': 'Slovakia'} c = {'fr': 'France'} # Sample-1: Double Asterisk Method md = {**a, **b, **c} print(md) # Sample-2: Update Method def merge_dics(diclist): td = {} for d in diclist: td.update(d) return td md = merge_dics([a, b, c]) print(md) # Sample-3: Update Method Via Class # (Facilitating Use Of + operator in lieu of __add__) class MergeDics(dict): def __add__(self, other): self.update(other) return MergeDics(self) md = MergeDics(a)+b+c print(md)The output in each case is as follows:
Output:{'de': 'Germany', 'sk': 'Slovakia', 'fr': 'France'}
A.D.Tejpal