- Python add to dictionary examples (7 different methods)
- Overview on Python Dictionary
- How to append or add key value pair to dictionary in Python
- Method-1: Python add keys and values to dictionary
- Method-2: Python add multiple keys and values to dictionary
- Method-3: Extract dictionary to append keys and values
- Method-4: Use dict.items() to list and add key value pairs into a dictionary
- Method-5: Use for loop to combine dictionary items
- Method-6: Python add to dictionary using dict.setdefault()
- Method-7: Python append dictionary using update operator
- Summary
- References
- Leave a Comment Cancel reply
- Python Tutorial
- Python Add to Dictionary – Adding an Item to a Dict
- How to Create a Dictionary in Python
- Features of a Dictionary
- Duplicate Keys Are Not Allowed
- Items in a Dictionary Are Changeable
- Items in a Dictionary Are Ordered
- How to Add an Item to a Dictionary
- Conclusion
Python add to dictionary examples (7 different methods)
Related Searches: python add to dictionary, python dictionary append, append to dictionary python, python add to dict, add values to dictionary python, how to add to a dictionary python, add to a dictionary python, add values to a dictionary python, how to append to a dictionary in python, python dictionary insert
Overview on Python Dictionary
A dictionary in Python is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the value associated with that key. A key’s value can be a number, a string, a list, or even another dictionary. In fact, you can use any object that you can create in Python as a value in a dictionary.
In Python, a dictionary is wrapped in braces, <> , with a series of key-value pairs inside the braces, as shown in the following example:
cars = 'maruti': 'omni', 'honda': 'jazz'>
How to append or add key value pair to dictionary in Python
Dictionaries are dynamic structures, and you can add new key-value pairs to a dictionary at any time. For example, to add a new key-value pair, you would give the name of the dictionary followed by the new key in square brackets along with the new value.
A key-value pair is a set of values associated with each other. When you provide a key, Python returns the value associated with that key. Every key is connected to its value by a colon, and individual key-value pairs are separated by commas. You can store as many key-value pairs as you want in a dictionary.
In all the methods covered as part of this tutorial, if the key already exists in the dictionary then it’s value will be updated instead of appending duplicate key.
Method-1: Python add keys and values to dictionary
This is most used and preferred method to add key-value pair to dictionary, with following syntax:
In this example we will add a new key value pair to an empty dictionary. Although you could use the same method with any dictionary with already contains some elements. In such case the newly added key value pair would be appended to the dictionary content.
#!/usr/bin/env python3 ## Define an empty dictionary mydict = <> # Add key and value to mydict mydict['key1'] = 'val1' # Print the content of mydict print('Add to empty dictionary: ', mydict) # Add one more key value pair mydict['key2'] = 'val2' # List content of mydict print('Append to dictionary: ', mydict)
Output from this script:
Method-2: Python add multiple keys and values to dictionary
In this previous example we added two set of key and value pair. But we had to perform this action twice for two set of key value pairs. In such cases if you have multiple key value pairs to be added to a dictionary then you can use dict.update()
#!/usr/bin/env python3 # My original dictionary mydict = 'name': 'admin', 'age': 32> # Create temporary dictionary which needs to be # added to original dictionary temp_dict = 'addr': 'India', 'hobby': 'blogging'> # Update the original dictionary with temp_dict content mydict.update(temp_dict) # Check the new content of original dictionary print(mydict)
If you do not wish to create a new temporary dictionary to append key value pair into original dictionary then you can also use the following syntax:
mydict.update('addr': 'India', 'hobby': 'blogging'>)
Method-3: Extract dictionary to append keys and values
With Python 3.5 and higher release we can use Unpacking feature. We can use ** dictionary unpacking operators to allow unpacking in more positions, an arbitrary number of times, and in additional circumstances.
#!/usr/bin/env python3 # My first dictionary orig_dict = 'name': 'admin', 'age': 32> # My second dictionary new_dict = 'addr': 'India', 'hobby': 'blogging'> # Append new dict content into orig dictionary orig_dict = <**orig_dict, **new_dict># Check the content of original dictionary print(orig_dict)
If you would like to append a single set of key-value pair using this method then following is one such example:
Here, we are extracting all the contents of orig_dict and appending addr: India only, instead of all the key-value pairs from new_dict . Output from this script:
Method-4: Use dict.items() to list and add key value pairs into a dictionary
In this example we will use dict.items() to list both the key-value pair of dictionary and then add them.
#!/usr/bin/env python3 # My first dictionary orig_dict = 'name': 'admin', 'age': 32> # My second dictionary new_dict = 'addr': 'India', 'hobby': 'blogging'> # Add new dict content into orig dictionary # Convert the output to dictionary using dict() orig_dict = dict(list(orig_dict.items()) + list(new_dict.items())) # Check the content of original dictionary print(orig_dict)
Method-5: Use for loop to combine dictionary items
In this method we will iterate over two dictionary items, combine them and store into a new dictionary.
#!/usr/bin/env python3 # My first dictionary mydict1 = 'name': 'admin', 'age': 32> # My second dictionary mydict2 = 'addr': 'India', 'hobby': 'blogging'> # Use for loop to iterate over both dictionaries and add them # to third dictionary new_dict = <> new_dict = dict( i for d in [mydict1,mydict2] for i in d.items() ) # Check the content of new dictionary print(new_dict)
Method-6: Python add to dictionary using dict.setdefault()
As per dict.setdefault() official documentation, if key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None .
#!/usr/bin/env python3 # My original dictionary orig_dict = 'name': 'admin', 'age': 32> # Use dict.setdefault() to add new key value pair orig_dict.setdefault('addr', 'India') # Check the content of original dictionary print(orig_dict)
Method-7: Python append dictionary using update operator
With Python 3.9 release we have an update operator which can be used to append or combine two dictionaries.
- d | other : Create a new dictionary with the merged keys and values of d and other, which must both be dictionaries. The values of other take priority when d and other share keys.
- d |= other : Update the dictionary d with keys and values from other, which may be either a mapping or an iterable of key/value pairs. The values of other take priority when d and other share keys.
Verify the Python version:
Here is a sample code to append dictionary as well as combine two dictionaries and create a new one:
#!/usr/bin/env python3 # My first dictionary dict1 = 'name': 'admin', 'age': 32> # My second dictionary dict2 = 'addr': 'India', 'hobby': 'blogging'> # Append dict1 dictionary with dict2 content dict1 |= dict2 # Create new dictionary by combining dict1 and dict2 new_dict = <> new_dict = dict1 | dict2 # List the content of both dictionaries print('Original Dictionary: ', dict1) print('New Dictionary: ', new_dict)
~]# python3.9 eg-7.py Original Dictionary: New Dictionary:
Summary
In this tutorial we explored different methods with examples to add or append to dictionary. Some of these methods are limited to newer releases of Python while others would work even with older releases of Python such as Python 2.X. You may try and choose the best method based on your requirement.
References
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Leave a Comment Cancel reply
Python Tutorial
- Python Multiline Comments
- Python Line Continuation
- Python Data Types
- Python Numbers
- Python List
- Python Tuple
- Python Set
- Python Dictionary
- Python Nested Dictionary
- Python List Comprehension
- Python List vs Set vs Tuple vs Dictionary
- Python if else
- Python for loop
- Python while loop
- Python try except
- Python try catch
- Python switch case
- Python Ternary Operator
- Python pass statement
- Python break statement
- Python continue statement
- Python pass Vs break Vs continue statement
- Python function
- Python call function
- Python argparse
- Python *args and **kwargs
- Python lambda function
- Python Anonymous Function
- Python optional arguments
- Python return multiple values
- Python print variable
- Python global variable
- Python copy
- Python counter
- Python datetime
- Python logging
- Python requests
- Python struct
- Python subprocess
- Python pwd
- Python UUID
- Python read CSV
- Python write to file
- Python delete file
- Python any() function
- Python casefold() function
- Python ceil() function
- Python enumerate() function
- Python filter() function
- Python floor() function
- Python len() function
- Python input() function
- Python map() function
- Python pop() function
- Python pow() function
- Python range() function
- Python reversed() function
- Python round() function
- Python sort() function
- Python strip() function
- Python super() function
- Python zip function
- Python class method
- Python os.path.join() method
- Python set.add() method
- Python set.intersection() method
- Python set.difference() method
- Python string.startswith() method
- Python static method
- Python writelines() method
- Python exit() method
- Python list.extend() method
- Python append() vs extend() in list
- Create your first Python Web App
- Flask Templates with Jinja2
- Flask with Gunicorn and Nginx
- Flask SQLAlchemy
Python Add to Dictionary – Adding an Item to a Dict
Ihechikara Vincent Abba
Data structures help us organize and store collections of data. Python has built-in data structures like Lists, Sets, Tuples and Dictionaries.
Each of these structures have their own syntax and methods for interacting with the data stored.
In this article, we’ll talk about Dictionaries, their features, and how to add items to them.
How to Create a Dictionary in Python
Dictionaries are made up of key and value pairs nested in curly brackets. Here’s an example of a Dictionary:
In the code above, we created a dictionary called devBio with information about a developer – the developer’s age is quite overwhelming.
Each key in the dictionary – name , age and language – has a corresponding value. A comma separates each key and value pair from another. Omitting the comma throws an error your way.
Before we dive into how we can add items to our dictionaries, let’s have a look at some of the features of a dictionary. This will help you easily distinguish them from other data structures in Python.
Features of a Dictionary
Here are some of the features of a dictionary in Python:
Duplicate Keys Are Not Allowed
If we create a dictionary that has two or multiple identical keys in it, the last key out of them will override the rest. Here’s an example:
We created three keys with an identical key name of name . When we printed our dictionary to the console, the last key having a value of «Chikara» overwrote the rest.
Let’s see the next feature.
Items in a Dictionary Are Changeable
After assigning an item to a dictionary, you can change its value to something different.
devBio = < "name": "Ihechikara", "age": 120, "language": "JavaScript" >devBio["age"] = 1 print(devBio) #
In the example above, we reassigned a new value to age . This will override the initial value we assigned when the dictionary was created.
We can also use the update() method to change the value of items in our dictionary. We can achieve the same result in the last example by using the update() method – that is: devBio.update() .
Items in a Dictionary Are Ordered
By being ordered, this means that the items in a dictionary maintain the order in which they were created or added. That order cannot change.
Prior to Python 3.7, dictionaries in Python were unordered.
In the next section, we will see how we can add items to a dictionary.
How to Add an Item to a Dictionary
The syntax for adding items to a dictionary is the same as the syntax we used when updating an item. The only difference here is that the index key will include the name of the new key to be created and its corresponding value.
Here’s what the syntax looks like: devBio[newKey] = newValue .
We can also use the update() method to add new items to a dictionary. Here’s what that would look like: devBio.update(newKey«: newValue>) .
devBio = < "name": "Ihechikara", "age": 120, "language": "JavaScript" >devBio["role"] = "Developer" print(devBio) #
Above, using the index key devBio[«role»] , we created a new key with the value of Developer .
In the next example, we will use the update() method.
devBio = < "name": "Ihechikara", "age": 120, "language": "JavaScript" >devBio.update() print(devBio) #
Above, we achieved the same result as in the last example by passing in the new key and its value into the update() method – that is: devBio.update() .
Conclusion
In this article, we learned what dictionaries are in Python, how to create them, and some of their features. We then saw two ways through which we can add items to our dictionaries.