Python Forum
Merging Dictionaries - Optimum Style?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Merging Dictionaries - Optimum Style?
#6
For merging multiple dictionaries, proposed function dics_merge(), that alerts the user regarding presence of duplicate keys, affording option to permit overwriting or not, is placed below:

# Merge Dictionaries:
da = {"a":5, "b":10, "c":15, "d":20, "e":25}
db = {"f":55, "g":60, "h":65, "i":70, "j":75}
dc = {"k":105, "b":110, "m":115, "d":120, "n":80}
dd = {"p":155, "a":160, "b":165, "q":170, "r":180}
de = {"k":100, "p":60, "j":70, "r":90}

def dics_merge(diclist):
    dk = []  # List of duplicate keys
    owr = False  # Overwrite Permission
    dmg1 = {**diclist[0]}  # Merge Result - No Overwrite
    dmg2 = {**diclist[0]}  # Merge Result - With Overwrite

    for d in diclist[1:]:
        dmg2 = {**dmg2, **d}
        for k, v in d.items():
            if k in dmg1:
                dk.append(k)
            else:
                dmg1.setdefault(k, v)

    if len(dk) > 0:
        print("Duplicate Keys Detected: ", dk)
        ow = input("Shall Overwrite Existing Contents? Y/N  ")
        if ow.lower() == "y":
            owr = True

    if owr == True:
        return dmg2
    else:
        return dmg1

d_merge = dics_merge([da, db, dc, dd, de])
print(d_merge)
Outputs are as follows:
(a) Duplicate Keys List:
Output:
['b', 'd', 'a', 'b', 'k', 'p', 'j', 'r']
(b) Merge Result With No OverWrite:
Output:
{'a': 5, 'b': 10, 'c': 15, 'd': 20, 'e': 25, 'f': 55, 'g': 60, 'h': 65, 'i': 70, 'j': 75, 'k': 105, 'm': 115, 'n': 80, 'p': 155, 'q': 170, 'r': 180}
© Merge Result With OverWrite:
Output:
{'a': 160, 'b': 165, 'c': 15, 'd': 120, 'e': 25, 'f': 55, 'g': 60, 'h': 65, 'i': 70, 'j': 70, 'k': 100, 'm': 115, 'n': 80, 'p': 60, 'q': 170, 'r': 90}
Suggestions for further fine tuning of the proposed function would be most welcome.
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 393 Mar-21-2024, 09:31 PM
Last Post: max22
  merging three dictionaries Skaperen 3 2,103 Oct-20-2020, 10:06 PM
Last Post: Skaperen
  merging dictionaries Skaperen 3 2,648 Nov-13-2018, 06:26 AM
Last Post: Skaperen
  merging two dictionaries Skaperen 17 11,227 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