However bash I merge 2 dictionaries successful a azygous look successful Python?

However bash I merge 2 dictionaries successful a azygous look successful Python?

I privation to merge 2 dictionaries into a fresh dictionary.

x = {'a': 1, 'b': 2}y = {'b': 3, 'c': 4}z = merge(x, y)>>> z{'a': 1, 'b': 3, 'c': 4}

At any time when a cardinal k is immediate successful some dictionaries, lone the worth y[k] ought to beryllium stored.


However tin I merge 2 Python dictionaries successful a azygous look?

For dictionaries x and y, their shallowly-merged dictionary z takes values from y, changing these from x.

  • Successful Python Three.9.Zero oregon larger (launched 17 October 2020, PEP-584, mentioned present):

    z = x | y
  • Successful Python Three.5 oregon larger:

    z = {**x, **y}
  • Successful Python 2, (oregon Three.Four oregon less) compose a relation:

    def merge_two_dicts(x, y): z = x.copy() # start with keys and values of x z.update(y) # modifies z with keys and values of y return z

    and present:

    z = merge_two_dicts(x, y)

Mentation

Opportunity you person 2 dictionaries and you privation to merge them into a fresh dictionary with out altering the first dictionaries:

x = {'a': 1, 'b': 2}y = {'b': 3, 'c': 4}

The desired consequence is to acquire a fresh dictionary (z) with the values merged, and the 2nd dictionary's values overwriting these from the archetypal.

>>> z{'a': 1, 'b': 3, 'c': 4}

A fresh syntax for this, projected successful PEP 448 and disposable arsenic of Python Three.5, is

z = {**x, **y}

And it is so a azygous look.

Line that we tin merge successful with literal notation arsenic fine:

z = {**x, 'foo': 1, 'bar': 2, **y}

and present:

>>> z{'a': 1, 'b': 3, 'foo': 1, 'bar': 2, 'c': 4}

It is present displaying arsenic applied successful the merchandise agenda for Three.5, PEP 478, and it has present made its manner into the What's Fresh successful Python Three.5 papers.

Nevertheless, since galore organizations are inactive connected Python 2, you whitethorn want to bash this successful a backward-appropriate manner. The classically Pythonic manner, disposable successful Python 2 and Python Three.Zero-Three.Four, is to bash this arsenic a 2-measure procedure:

z = x.copy()z.update(y) # which returns None since it mutates z

Successful some approaches, y volition travel 2nd and its values volition regenerate x's values, frankincense b volition component to 3 successful our last consequence.

Not but connected Python Three.5, however privation a azygous look

If you are not but connected Python Three.5 oregon demand to compose backward-appropriate codification, and you privation this successful a azygous look, the about performant piece the accurate attack is to option it successful a relation:

def merge_two_dicts(x, y): """Given two dictionaries, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z

and past you person a azygous look:

z = merge_two_dicts(x, y)

You tin besides brand a relation to merge an arbitrary figure of dictionaries, from zero to a precise ample figure:

def merge_dicts(*dict_args): """ Given any number of dictionaries, shallow copy and merge into a new dict, precedence goes to key-value pairs in latter dictionaries. """ result = {} for dictionary in dict_args: result.update(dictionary) return result

This relation volition activity successful Python 2 and Three for each dictionaries. e.g. fixed dictionaries a to g:

z = merge_dicts(a, b, c, d, e, f, g) 

and cardinal-worth pairs successful g volition return priority complete dictionaries a to f, and truthful connected.

Critiques of Another Solutions

Don't usage what you seat successful the previously accepted reply:

z = dict(x.items() + y.items())

Successful Python 2, you make 2 lists successful representation for all dict, make a 3rd database successful representation with dimension close to the dimension of the archetypal 2 option unneurotic, and past discard each 3 lists to make the dict. Successful Python Three, this volition neglect due to the fact that you're including 2 dict_items objects unneurotic, not 2 lists -

>>> c = dict(a.items() + b.items())Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'

and you would person to explicitly make them arsenic lists, e.g. z = dict(list(x.items()) + list(y.items())). This is a discarded of assets and computation powerfulness.

Likewise, taking the federal of items() successful Python Three (viewitems() successful Python 2.7) volition besides neglect once values are unhashable objects (similar lists, for illustration). Equal if your values are hashable, since units are semantically unordered, the behaviour is undefined successful regards to priority. Truthful don't bash this:

>>> c = dict(a.items() | b.items())

This illustration demonstrates what occurs once values are unhashable:

>>> x = {'a': []}>>> y = {'b': []}>>> dict(x.items() | y.items())Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unhashable type: 'list'

Present's an illustration wherever y ought to person priority, however alternatively the worth from x is retained owed to the arbitrary command of units:

>>> x = {'a': 2}>>> y = {'a': 1}>>> dict(x.items() | y.items()){'a': 2}

Different hack you ought to not usage:

z = dict(x, **y)

This makes use of the dict constructor and is precise accelerated and representation-businesslike (equal somewhat much truthful than our 2-measure procedure) however until you cognize exactly what is occurring present (that is, the 2nd dict is being handed arsenic key phrase arguments to the dict constructor), it's hard to publication, it's not the supposed utilization, and truthful it is not Pythonic.

Present's an illustration of the utilization being remediated successful django.

Dictionaries are supposed to return hashable keys (e.g. frozensets oregon tuples), however this technique fails successful Python Three once keys are not strings.

>>> c = dict(a, **b)Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: keyword arguments must be strings

From the mailing database, Guido van Rossum, the creator of the communication, wrote:

I americium good withdeclaring dict({}, **{1:Three}) amerciable, since last each it is maltreatment ofthe ** mechanics.

and

Seemingly dict(x, **y) is going about arsenic "chill hack" for "callx.replace(y) and instrument x". Personally, I discovery it much despicable thancool.

It is my knowing (arsenic fine arsenic the knowing of the creator of the communication) that the supposed utilization for dict(**y) is for creating dictionaries for readability functions, e.g.:

dict(a=1, b=10, c=11)

alternatively of

{'a': 1, 'b': 10, 'c': 11}

Consequence to feedback

Contempt what Guido says, dict(x, **y) is successful formation with the dict specification, which btw. plant for some Python 2 and Three. The information that this lone plant for drawstring keys is a nonstop effect of however key phrase parameters activity and not a abbreviated-coming of dict. Nor is utilizing the ** function successful this spot an maltreatment of the mechanics, successful information, ** was designed exactly to walk dictionaries arsenic key phrases.

Once more, it doesn't activity for Three once keys are not strings. The implicit calling declaration is that namespaces return average dictionaries, piece customers essential lone walk key phrase arguments that are strings. Each another callables enforced it. dict broke this consistency successful Python 2:

>>> foo(**{('a', 'b'): None})Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: foo() keywords must be strings>>> dict(**{('a', 'b'): None}){('a', 'b'): None}

This inconsistency was atrocious fixed another implementations of Python (PyPy, Jython, IronPython). Frankincense it was mounted successful Python Three, arsenic this utilization might beryllium a breaking alteration.

I subject to you that it is malicious incompetence to deliberately compose codification that lone plant successful 1 interpretation of a communication oregon that lone plant fixed definite arbitrary constraints.

Much feedback:

dict(x.items() + y.items()) is inactive the about readable resolution for Python 2. Readability counts.

My consequence: merge_two_dicts(x, y) really appears overmuch clearer to maine, if we're really afraid astir readability. And it is not guardant appropriate, arsenic Python 2 is progressively deprecated.

{**x, **y} does not look to grip nested dictionaries. the contents of nested keys are merely overwritten, not merged [...] I ended ahead being burnt by these solutions that bash not merge recursively and I was amazed nary 1 talked about it. Successful my explanation of the statement "merging" these solutions depict "updating 1 dict with different", and not merging.

Sure. I essential mention you backmost to the motion, which is asking for a shallow merge of 2 dictionaries, with the archetypal's values being overwritten by the 2nd's - successful a azygous look.

Assuming 2 dictionaries of dictionaries, 1 mightiness recursively merge them successful a azygous relation, however you ought to beryllium cautious not to modify the dictionaries from both origin, and the surest manner to debar that is to brand a transcript once assigning values. Arsenic keys essential beryllium hashable and are normally so immutable, it is pointless to transcript them:

from copy import deepcopydef dict_of_dicts_merge(x, y): z = {} overlapping_keys = x.keys() & y.keys() for key in overlapping_keys: z[key] = dict_of_dicts_merge(x[key], y[key]) for key in x.keys() - overlapping_keys: z[key] = deepcopy(x[key]) for key in y.keys() - overlapping_keys: z[key] = deepcopy(y[key]) return z

Utilization:

>>> x = {'a':{1:{}}, 'b': {2:{}}}>>> y = {'b':{10:{}}, 'c': {11:{}}}>>> dict_of_dicts_merge(x, y){'b': {2: {}, 10: {}}, 'a': {1: {}}, 'c': {11: {}}}

Coming ahead with contingencies for another worth varieties is cold past the range of this motion, truthful I volition component you astatine my reply to the canonical motion connected a "Dictionaries of dictionaries merge".

Little Performant However Accurate Advertisement-hocs

These approaches are little performant, however they volition supply accurate behaviour.They volition beryllium overmuch little performant than copy and update oregon the fresh unpacking due to the fact that they iterate done all cardinal-worth brace astatine a increased flat of abstraction, however they bash regard the command of priority (second dictionaries person priority)

You tin besides concatenation the dictionaries manually wrong a dict comprehension:

{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7

oregon successful Python 2.6 (and possibly arsenic aboriginal arsenic 2.Four once generator expressions had been launched):

dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2

itertools.chain volition concatenation the iterators complete the cardinal-worth pairs successful the accurate command:

from itertools import chainz = dict(chain(x.items(), y.items())) # iteritems in Python 2

Show Investigation

I'm lone going to bash the show investigation of the usages recognized to behave appropriately. (Same-contained truthful you tin transcript and paste your self.)

from timeit import repeatfrom itertools import chainx = dict.fromkeys('abcdefg')y = dict.fromkeys('efghijk')def merge_two_dicts(x, y): z = x.copy() z.update(y) return zmin(repeat(lambda: {**x, **y}))min(repeat(lambda: merge_two_dicts(x, y)))min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))min(repeat(lambda: dict(chain(x.items(), y.items()))))min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))

Successful Python Three.Eight.1, NixOS:

>>> min(repeat(lambda: {**x, **y}))1.0804965235292912>>> min(repeat(lambda: merge_two_dicts(x, y)))1.636518670246005>>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))3.1779992282390594>>> min(repeat(lambda: dict(chain(x.items(), y.items()))))2.740647904574871>>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))4.266070580109954
$ uname -aLinux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux

Assets connected Dictionaries


Successful your lawsuit, you tin bash:

z = dict(list(x.items()) + list(y.items()))

This volition, arsenic you privation it, option the last dict successful z, and brand the worth for cardinal b beryllium decently overridden by the 2nd (y) dict's worth:

>>> x = {'a': 1, 'b': 2}>>> y = {'b': 10, 'c': 11}>>> z = dict(list(x.items()) + list(y.items()))>>> z{'a': 1, 'c': 11, 'b': 10}

If you usage Python 2, you tin equal distance the list() calls. To make z:

>>> z = dict(x.items() + y.items())>>> z{'a': 1, 'c': 11, 'b': 10}

If you usage Python interpretation Three.9.0a4 oregon higher, you tin straight usage:

>>> x = {'a': 1, 'b': 2}>>> y = {'b': 10, 'c': 11}>>> z = x | y>>> z{'a': 1, 'c': 11, 'b': 10}

Merging dictionaries is a communal project successful Python programming. Dictionaries are versatile information buildings, and combining them into a azygous dictionary effectively is important for assorted functions. This article explores antithetic strategies to merge 2 oregon much dictionaries into 1 utilizing a azygous look. We'll screen the about Pythonic and performant approaches, making certain your codification stays cleanable and effectual. Knowing these strategies volition empower you to grip information aggregation and configuration direction with easiness.

However tin I harvester 2 dictionaries successful Python successful 1 spell?

Successful Python, location are respective methods to merge dictionaries successful a azygous formation of codification. 1 of the about easy approaches includes utilizing the function, which unpacks the dictionaries into a fresh dictionary. This methodology is concise and readable, making it a favourite amongst Python builders. Different communal methodology is utilizing the .replace() methodology, which merges the contents of 1 dictionary into different. The prime betwixt these strategies frequently relies upon connected the circumstantial necessities of your codification, specified arsenic whether or not you demand to make a fresh dictionary oregon modify an present 1. We'll delve into these strategies with broad examples to usher you done the procedure.

Utilizing the Function to Merge Dictionaries

The function, besides identified arsenic the treble asterisk oregon unpack function, provides a cleanable and businesslike manner to merge dictionaries. This function unpacks the cardinal-worth pairs from all dictionary and combines them into a fresh dictionary. This attack is peculiarly utile once you privation to make a fresh merged dictionary with out modifying the first dictionaries. Successful instances wherever location are overlapping keys, the cardinal-worth brace from the dictionary showing future successful the look volition overwrite the earlier 1. This behaviour makes it predictable and casual to ground astir. The function has go a modular manner to merge dictionaries successful Python Three.5 and future owed to its conciseness and readability. For much insights into Python operators, cheque retired this PEP 448.

  dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} merged_dict = {dict1, dict2} print(merged_dict) Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}  

Merging with the .replace() Methodology

The .replace() methodology is different manner to merge dictionaries, however it plant by modifying an present dictionary instead than creating a fresh 1. This methodology takes different dictionary (oregon an iterable of cardinal-worth pairs) arsenic an statement and provides its contents to the dictionary it's known as connected. If location are overlapping keys, the values from the dictionary handed to .replace() volition overwrite the present values. This attack is utile once you privation to modify a dictionary successful spot. Support successful head that since .replace() modifies the first dictionary, it does not instrument a fresh dictionary, however alternatively returns No. The .replace() methodology is a cardinal portion of Python's dictionary API, providing an successful-spot merging resolution. Present is an absorbing station: Nevertheless bash I cheque whether or not oregon not a evidence exists with retired exceptions?

  dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} dict1.update(dict2) print(dict1) Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}  

See this script:

  dict1 = {'a': 1, 'b': 2} dict2 = {'a': 3, 'd': 4} dict1.update(dict2) print(dict1) Output: {'a': 3, 'b': 2, 'd': 4}  

Successful this lawsuit, the worth of 'a' successful dict1 is overwritten by the worth of 'a' successful dict2.

Alternate options for Combining Dictionaries

Piece the function and the .replace() methodology are the about communal methods to merge dictionaries successful Python, location are another approaches you tin usage, peculiarly for much analyzable situations. These alternate options mightiness affect utilizing loops oregon dictionary comprehensions, particularly once you demand to use conditional logic throughout the merging procedure. For case, you mightiness privation to merge dictionaries lone if definite circumstances are met oregon execute any translation connected the values throughout the merge. These alternate strategies message larger flexibility however mightiness travel astatine the outgo of accrued codification complexity. Knowing these choices permits you to tailor your dictionary merging scheme to the circumstantial wants of your exertion.

Utilizing Dictionary Comprehensions

Dictionary comprehensions supply a concise manner to make dictionaries primarily based connected present iterables. They tin besides beryllium utilized to merge dictionaries with any further logic. This methodology includes iterating complete the cardinal-worth pairs of the dictionaries you privation to merge and setting up a fresh dictionary primarily based connected these pairs. Dictionary comprehensions are peculiarly utile once you demand to filter oregon change the cardinal-worth pairs throughout the merge procedure. They message a versatile and readable manner to execute much analyzable dictionary merging operations. For a deeper dive into dictionary comprehensions, research the authoritative Python documentation present.

  dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} merged_dict = {k: v for d in (dict1, dict2) for k, v in d.items()} print(merged_dict) Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}  

For a lawsuit wherever location are overlapping keys, the values of the 2nd dictionary volition override the archetypal 1.

Utilizing the ChainMap People

The ChainMap people from the collections module gives a manner to nexus aggregate dictionaries unneurotic into a azygous position. Dissimilar the former strategies, ChainMap does not make a fresh dictionary. Alternatively, it creates a database of dictionaries that are searched successful series. This tin beryllium utile once you person aggregate dictionaries representing antithetic scopes oregon layers of configuration. Once you entree a cardinal successful a ChainMap, it searches the dictionaries successful the command they have been added till it finds the cardinal. If the cardinal is not recovered successful immoderate of the dictionaries, it raises a KeyError. The ChainMap is businesslike for publication operations, arsenic it avoids creating a fresh dictionary, however it tin beryllium little businesslike for compose operations, arsenic it lone modifies the archetypal dictionary successful the concatenation that comprises the cardinal. For much accusation, sojourn the Python collections module documentation.

  from collections import ChainMap dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} merged_dict = ChainMap(dict1, dict2) print(merged_dict['a']) Output: 1 print(merged_dict['c']) Output: 3  
Methodology Creates Fresh Dictionary Modifies First Dictionary Usage Lawsuit
Function Sure Nary Elemental merging with out modifying originals
.replace() Methodology Nary Sure Successful-spot merging
Dictionary Comprehensions Sure Nary Merging with conditional logic
ChainMap Nary Nary (gives a position) Linking aggregate dictionaries with out merging

Successful decision, merging dictionaries successful Python tin beryllium achieved successful respective methods, all with its ain advantages and usage instances. The function gives a concise and readable manner to make a fresh merged dictionary. The .replace() methodology permits for successful-spot modification of an present dictionary. Dictionary comprehensions message flexibility for merging with conditional logic, and ChainMap gives a linked position of aggregate dictionaries with out creating a fresh 1. Selecting the correct methodology relies upon connected the circumstantial necessities of your project. Experimentation with these strategies to discovery the about businesslike and readable resolution for your codification. Blessed coding!


Previous Post Next Post

Formulario de contacto