I am using Python and I want to join these two dictionaries:
dic1 = {1:"hola", 2:"adios", 3:"hasta luego"}
dic2 = {4:"¿Cómo estás?", 5:"¿Te encuentras bien?"}
How can I do it?
For now I had tried this, joining everything in dic3
, but it seems to me that I do a lot of transformations and it's inelegant:
dic1 = {1:"hola", 2:"adios", 3:"hasta luego"}
dic2 = {4:"¿Cómo estás?", 5:"¿Te encuentras bien?"}
#Uso el método items y list para crearme una lista
tuple_dic1 = list(dic1.items())
tuple_dic2 = list(dic2.items())
#los uno como lista y devuelvo un diccionario unido
dic3 = dict(tuple_dic1 + tuple_dic2)
On the other hand, dictionaries cannot have repeated keys, so in the event that there are repeated keys, what is the key that Python will keep? and how does it work?
For example in these two cases where the key 1
is repeated but with a different value:
dic1 = {1:"hola", 2:"adios", 3:"hasta luego"}
dic2 = {4:"¿Cómo estás?", 5:"¿Te encuentras bien?", 1:"Buenos días"}
Python => 3.9
If the Python version is 3.9 or later, there is the operator
|
and the operator|=
defined as merge and update operators respectively. So to join the dictionaries we would execute the following code:Departure:
If we want to update an existing dictionary , we use the aforementioned operator
|=
:Departure:
Although the output is the same, in the first output we have had to create a third dictionary and in the second, we have updated
dic1
.This can be found in the documentation for new Python releases in summary form What's New In Python 3.9 . And in more detail in the PEP584 documentation
Versions prior to Python 3.9
This method represents a great advance in the ease of use of Python, and replaces previous methods that are ugly or not so easily understood by people with little experience in the language.
Union of dictionaries before Python 3.9
Updating dictionaries before Python 3.9
What happens if we use the same key?
In both ways, the last key in the dictionary will always remain. It is logical that Python works like this, since the second dictionary would be an update on the first one, therefore, in case of a repeated key, the last dictionary always remains. Example:
Departure:
I repeat, this will happen the same in Python 3.9, as in previous versions