Python Forum
Merging Dictionaries - Optimum Style?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Merging Dictionaries - Optimum Style?
#2
More or less it's a preference between 1 and 2 and will depend on use case
The third one is tricky as at least first term should be MergeDict, i.e. I think it's overkill
Also note that __add__() can return self, no need to do MergeDict(self), self is already instance of MergeDict class
Just to add timeing for methods 1 and 2
# Merging Dictionaries: Different Styles
a = {'de': 'Germany'}
b = {'sk': 'Slovakia'}
c = {'fr': 'France'}

from timeit import timeit
# Sample-2: Update Method
def merge_dicts(diclist):
    td = {}
    for d in diclist:
        td.update(d)
    return td
 

print(timeit(stmt='md = {**a, **b, **c}', setup='from __main__ import a, b, c', number=100000))
print(timeit(stmt='md = merge_dicts([a, b, c])', setup='from __main__ import a, b, c, merge_dicts', number=100000))
Output:
0.05819004499994662 0.24759990400002607
clearly, star unpacking is faster
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
Merging Dictionaries - Optimum Style? - by adt - Oct-09-2019, 06:45 AM
RE: Merging Dictionaries - Optimum Style? - by buran - Oct-09-2019, 07:07 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 304 Mar-21-2024, 09:31 PM
Last Post: max22
  merging three dictionaries Skaperen 3 2,010 Oct-20-2020, 10:06 PM
Last Post: Skaperen
  merging dictionaries Skaperen 3 2,512 Nov-13-2018, 06:26 AM
Last Post: Skaperen
  merging two dictionaries Skaperen 17 10,746 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