Python Forum
Merging Dictionaries - Optimum Style?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Merging Dictionaries - Optimum Style?
#1
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).

# 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
Reply


Messages In This Thread
Merging Dictionaries - Optimum Style? - by adt - Oct-09-2019, 06:45 AM
RE: Merging Dictionaries - Optimum Style? - by adt - Oct-09-2019, 08:09 AM
RE: Merging Dictionaries - Optimum Style? - by adt - Oct-09-2019, 05:26 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  optimum chess endgame with D=3 pieces doesn't give an exact moves_to_mate variable max22 1 272 Mar-21-2024, 09:31 PM
Last Post: max22
  merging three dictionaries Skaperen 3 1,990 Oct-20-2020, 10:06 PM
Last Post: Skaperen
  merging dictionaries Skaperen 3 2,485 Nov-13-2018, 06:26 AM
Last Post: Skaperen
  merging two dictionaries Skaperen 17 10,658 Oct-05-2017, 12:47 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020