Friday, September 17, 2021

Python for Beginners: Add an item to a dictionary in Python

A dictionary in python is a data structure that stores data in the form of key-value pairs. The key-value pairs are also called items. The key-value pairs in each dictionary are separated by a colon “:” and each item in the dictionary is separated by a comma “,”. In this article, we will look at different ways to add an item to a dictionary in python.

Add an item to a dictionary using subscript notation

If we have a dictionary named myDict and a key-value pair having values myKey and myValue, then we can add the key-value pair to the dictionary using the syntax myDict [ myKey ] = myValue. This can be done as follows.

myDict = {"name": "PythonForBeginners", "acronym": "PFB"}
print("Original Dictionary is:", myDict)
myDict["niche"] = "programming"
print("Modified Dictionary is:", myDict)

Output:

Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}

In the example above, we have added a new key “niche” with value “programming” associated with it.

Remember that if the key of the item which is being added to the dictionary already exists in it, the value for the key will be overwritten with a new value. This can be seen in the following example.

myDict = {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
print("Original Dictionary is:", myDict)
myDict["niche"] = "python programming"
print("Modified Dictionary is:", myDict)

Output:

Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'python programming'}

In the example above, the key “niche” already exists in the dictionary with value “programming” associated with it. When we try to add the key-value pair with “niche” as key and “python programming” as associated value, the value associated with “niche” is updated to the new value.

Add an item to a dictionary using the update() method in Python

We can add an item to a dictionary using the update() method. The update() method when invoked on a dictionary, takes a dictionary or an iterable object having key-value pairs as input and adds the items to the dictionary.

We can give a  new dictionary as an input to the update() method and add the items to a given dictionary as follows.

myDict = {"name": "PythonForBeginners", "acronym": "PFB"}
print("Original Dictionary is:", myDict)
myDict.update({'niche': 'programming'})
print("Modified Dictionary is:", myDict)

Output:

Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}

We can give a list of tuples having key-value pairs as an input to the update() method and add items to a given dictionary as follows.

myDict = {"name": "PythonForBeginners", "acronym": "PFB"}
print("Original Dictionary is:", myDict)
items = [("niche", "programming")]
myDict.update(items)
print("Modified Dictionary is:", myDict)

Output:

Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}

We can also pass key-value pairs as keyword parameters to the update() method to add elements to the dictionary. Here the keys will be used as keyword parameters and values will be assigned as an input to the keyword parameters as follows.

myDict = {"name": "PythonForBeginners", "acronym": "PFB"}
print("Original Dictionary is:", myDict)
myDict.update(niche="programming")
print("Modified Dictionary is:", myDict)

Output:

Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}

Add an item to a dictionary using the ** operator in Python

A double asterisk (**) operator is used to pass variable length keyword parameters to a function. We can also use the ** operator to add a key-value pair to another dictionary. When we apply the ** operator to a dictionary, it deserializes the dictionary and converts it to a collection of key-value pairs. This collection of key-value pairs can be again converted to a dictionary.

To add an item to a dictionary, we will first create a dictionary with only that item. Then we will use the ** operator to merge the new dictionary and the dictionary to which the item had to be added as follows.

myDict = {"name": "PythonForBeginners", "acronym": "PFB"}
print("Original Dictionary is:", myDict)
newDict = {'niche': 'programming'}
myDict = {**myDict, **newDict}
print("Modified Dictionary is:", myDict)

Output:

Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}

Add an item to a dictionary using the __setitem__() method

We can also add an item to the dictionary using the __setitem__() method. The __setitem__() method, when invoked on a dictionary, takes the new key and value as its first and second parameters respectively and adds the key-value pair to the dictionary as follows.

myDict = {"name": "PythonForBeginners", "acronym": "PFB"}
print("Original Dictionary is:", myDict)
myDict.__setitem__('niche', 'programming')
print("Modified Dictionary is:", myDict)

Output:

Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}

If the key already exists in the dictionary, the value associated with it is overwritten with the new value. This can be seen in the following example.

myDict = {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
print("Original Dictionary is:", myDict)
myDict.__setitem__('niche', 'python programming')
print("Modified Dictionary is:", myDict)

Output:

Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'python programming'}

Conclusion

In this article, we have seen different ways to add an item to a dictionary in python. To read more about dictionaries in python you can read this article on dictionary comprehension or this article on how to merge two dictionaries in python.

The post Add an item to a dictionary in Python appeared first on PythonForBeginners.com.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...