Thursday, October 22, 2020

Python- How to Merge two Dictionaries

Python Dictionaries
If you are working as Python developer, data analytics or data scientists for any organisation then it is very important for you to know how to merge two dictionaries.

In Python, Dictionaries are written with curly brackets{}, and they are the combination of keys and values (key: value). The basic use of dictionaries in Python to store data values like a map, which unlike other Data Types that hold only single value as an element. Dictionaries is known as a collection which is unordered, changeable and indexed. If you knows about your keys in dictionaries then you can optimized it to retrieve values in a better ways.

Suppose that you have to add two dictionaries x and y in Python as given below -

By creating a normal function — There is a very simple way to define a function in python by taking two dictionary variables as given below -

Now, you have to call the above function to merge two dictionaries as given below -

Efficient Way :Use lambda functionality — Some Python users think that lambdas are evil because lambda expressions are an odd and unfamiliar syntax to many Python programmers. But Lambdas are closures, which makes the space savings even bigger, since now you don’t have to add a parameterized constructor, fields, assignment code, etc to your replacement class.

You can write the fast and memory-efficient solution with one expression:

As suggested above, using two lines of code or writing a function is probably a better way to go.
To learn more, please follow us -
http://www.sql-datatools.com
To Learn more, please visit our YouTube channel at —
http://www.youtube.com/c/Sql-datatools
To Learn more, please visit our Instagram account at -
https://www.instagram.com/asp.mukesh/
To Learn more, please visit our twitter account at -
https://twitter.com/macxima
To Learn more, please visit our Medium account at -
https://medium.com/@macxima

No comments:

Post a Comment