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.

Advertisement

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.

IMPORTANT NOTE:

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:

dictionary[key] = value

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.

Advertisement
#!/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:
Python add to dictionary examples (7 different methods)

 

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'})

Output from this script:

~]# python3 eg-2.py
{'name': 'admin', 'age': 32, '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)

Output from this script:

~]# python3 eg-3.py
{'name': 'admin', 'age': 32, 'addr': 'India', 'hobby': 'blogging'}

If you would like to append a single set of key-value pair using this method then following is one such example:

orig_dict = {**orig_dict, **{'addr':'India'}}

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:

{'name': 'admin', 'age': 32, 'addr': 'India'}

 

Advertisement

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)

Output from this script:

~]# python3 eg-4.py
{'name': 'admin', 'age': 32, 'addr': 'India', 'hobby': 'blogging'}

 

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)

Output from this script:

~]# python3 eg-5.py
{'name': 'admin', 'age': 32, 'addr': 'India', 'hobby': 'blogging'}

 

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)

Output from this script:

~]# python3 eg-6.py
{'name': 'admin', 'age': 32, 'addr': 'India'}

 

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:

Advertisement
~]# python3.9 -V
Python 3.9.1

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)

Output from this script:

~]# python3.9 eg-7.py
Original Dictionary:  {'name': 'admin', 'age': 32, 'addr': 'India', 'hobby': 'blogging'}
New Dictionary:  {'name': 'admin', 'age': 32, 'addr': 'India', 'hobby': 'blogging'}

 

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

How can I add new keys to a dictionary?
Python3 built-in libraries

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.

Buy GoLinuxCloud a Coffee

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