×

Append key Value to Dictionary in Python

The Python dictionary is one of the built-in data types. Elements of dictionaries are key-value pairs. In Python, there are numerous ways to add dictionaries. Let's examine some of the multiple approaches to adding or appending things to a Python dictionary.

Basically, one of the significant data types offered by Python is the dictionary. A dictionary stores information as a key/value pair. The key/value pair is distinguished from it by a comma (,), and a colon distinguishes it (:).

A dictionary's keys are distinct and can be any combination of a string, tuple, number, etc. The values could be a list inside another list, an integer, etc.

Let’s take a brief introduction to Dictionary in Python.

Dictionary in Python

A dictionary is used to store and manage values in key-value pairs, in which the key is mapped to its corresponding value, as opposed to other data types that can only retain a single value as an element. A dictionary's keys, which can be strings, numbers, or tuples, must be immutable even though the dictionary's entries can be of any kind.

A dictionary is ordered, modifiable, and prevents redundancy. A dictionary is defined in terms of syntax by enclosing a list of key-value pairs in curly brackets (i.e. ). Each key and its corresponding value are separated by a colon (:) and each pair of keys and values is separated by a comma (,).

Let’s understand it by taking an example:

Example

student = {'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76}
print(student)
print(type(student))

Output

{'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76}

<class 'dict'>

Append New Key-value pair to Python Dictionary

In python, we can add new key-value pairs using 2 methods.

  1. By using the [] operator
  2. By using the update() method

1.By using the [] operator

We can add or append the new key-value pair in python using the [] operator. To add new key-value pair, the syntax is given below.

dict_name [ new_key ] = value

Let’s understand this by the example.

Example

student = { 'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76 }
print( f'''value of the student before adding new key-value pair: 
{student}
''' )
student[ 'grade' ] = 'A'
print( f'''value of the student after adding new key-value pair: 
{student}
''' )

Output

value of the student before adding new key-value pair: 
{ 'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76 }


value of the student after adding new key-value pair: 
{ 'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76, 'grade': 'A' }

2. By using the update() method

We can append a dictionary to another dictionary using the update() method provided by the Python dictionary. The update() method automatically replaces old key values with new ones. Therefore, be careful not to replace any important information at this place.

Let's examine how we may update our dictionary with new values using the dictionary update() method:

Example

student = { 'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76 }
print( f'''value of the student before adding new key-value pair: 
{student}
''' )
student.update( { 'grade': 'A' } )
print( f'''value of the student after adding new key-value pair: 
{student}
''' )

Output

value of the student before adding new key-value pair: 
{ 'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76 }


value of the student after adding new key-value pair: 
{ 'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76, 'grade': 'A' }

We can use the update function if the key is a type of string. The new key-value pair can be added as shown below

dict_name.update( key=value )

Let’s understand it with the help of an example.

student = { 'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76 }
print( f'''value of the student before adding new key-value pair: 
{student}
''' )
student.update( grade='A' )
print( f'''value of the student after adding new key-value pair: 
{student}
''' )

Output

value of the student before adding new key-value pair: 
{ 'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76 }


value of the student after adding new key-value pair: 
{ 'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76, 'grade': 'A' }

Don't overwrite the Python dictionary while adding entries

Remember that both methods will automatically overwrite any existing value if the key exists. Instead of immediately adding the values, it is preferable to use a conditional append if you anticipate that your software may produce duplicate keys.

To ensure that the keys in the dictionary are not overwritten, we can do the same thing here by using an if condition.

Here is a straightforward illustration of how to make this work. However, you have the option of employing the try-catch exception; starting with an if condition will be the simplest.

Adding Value to Existing Keys

Sometimes a key can be associated with values that can be a list or tuple. There is no in-built function to add value to that key directly. In this case, we can use the below function.

def add_multiple_values( entry: dict, key, value ):
    # checking if the key already exists or not
    if key in entry.keys():
        # checking if the value is list or not
        if isinstance( entry[ key ], list ):
            # appending the value
            entry[ key ].append( value )
        else:
            # converting the value in list type
            entry[ key ] = list( [entry[ key ]] )
            entry[ key ].append( value )
    else:
        # creating new key-value pair if the key is not exist
        entry[ key ] = value

By the use of the above function, we can add multiple values to a single key. If the key is not present in the dictionary then it will create a new key-value pair. If the key already exists then it will check the type of associated value. If the value is the type of list then it will append the new value. If the value is not the type of list then first it will convert it to the list then it will append the new value.

Let’s understand the above example with the help of an example.

Example

def add_multiple_values( entry: dict, key, value ):
    # checking if the key already exists or not
    if key in entry.keys():
        # checking if the value is list or not
        if isinstance( entry[ key ], list ):
            # appending the value
            entry[ key ].append( value )
        else:
            # converting the value in list type
            entry[ key ] = list( [entry[ key ]] )
            entry[ key ].append( value )
    else:
        # creating new key-value pair if the key is not exist
        entry[ key ] = value




# creating the dictionary named student having multiple key-value pairs.
student = { 'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76, 'subjects': 'DSA' }


# printing the student dictionary before updating it
print( f'''value of the student dictionary before adding new key-value pair: 
{student}
''' )


# updating the student dictionary
add_multiple_values( student, 'subjects', 'BDA' )


# printing the student dictionary after updating it
print( f'''value of the student dictionary after adding new key-value pair: 
{student}
''' )

Output

value of the student dictionary before adding new key-value pair: 
{'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76, 'subjects': 'DSA'}


value of the student dictionary after adding new key-value pair: 
{'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76, 'subjects': ['DSA', 'BDA']}

In the above example, we have a dictionary student. The dictionary has a key subject.

The value of the subject is ‘ DSA ’. If we want to append the new value ‘ BDA ’ then we can use the add_multiple_values() function to append BDA in the subject. The subjects key already exists, so it will check the type to value associated with it which is ‘ DSA ’. ‘DSA ’ is the type of string so it will convert it into a list. After converting it into the list now it will append ‘ BDA ’ to the list.

Add more than One Key-value Pair to Dictionary

We can give a dictionary or list of tuples containing new key-value pairs to update since that function accepts an iterable sequence of key-value pairs (). The specified key-value pairs will all be added to the dictionary; if a key already exists, the value will be updated.

Here we use the update() function to add multiple key-value pairs to the dictionary.

Let’s understand it by taking an example:

Exampl

# creating the dictionary named student having multiple key-value pairs.
student = { 'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76 }


# printing the student dictionary before updating it
print( f'''value of the student dictionary before adding new key-value pair: 
{student}
''' )


# new key-value pairs
new_key_value = [ ( 'grade', 'A' ), ( 'subject', 'DSA' ), ( 'batch', 'E4' ), ( 'semester', 4 ) ]


# updating the student dictionary
student.update( new_key_value )


# printing the student dictionary after updating it
print( f'''value of the student dictionary after adding new key-value pair: 
{student}
''' )

Output

value of the student dictionary before adding new key-value pair: 
{'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76}


value of the student dictionary after adding new key-value pair: 
{'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76, 'grade': 'A', 'subject': 'DSA', 'batch': 'E4', 'semester': 4}

In the above example, we have the dictionary student. Then we created a list of key-value pairs. By using the update method we can add all key-value pairs to the student dictionary.

Let’s understand to add more than one key-value pair to the dictionary by taking one other example

Example:

# creating the dictionary named person having multiple key-value pairs.
person = {'name': 'xyz', 'city': 'jaipur', 'age': 33}


# printing the student dictionary before updating it
print(f'''value of the person dictionary before adding new key-value pair: 
{person}
''')


# new key-value pairs
new_key_value = [('salary', 50000), ('category', 'gen'), ('Date of birth', '15-11-2002')]


# updating the person dictionary
person.update(new_key_value)


# printing the person dictionary after updating it
print(f'''value of the person dictionary after adding new key-value pair: 
{person}
''')

Output

value of the person dictionary before adding new key-value pair: 
{'name': 'xyz', 'city': 'jaipur', 'age': 33}


value of the person dictionary after adding new key-value pair: 
{'name': 'xyz', 'city': 'jaipur', 'age': 33, 'salary': 50000, 'category': 'gen', 'Date of birth': '15-11-2002'}

Adding Value from Another Dictionary

We can add key-value pairs to the dictionary from another dictionary by using the update() method.

Basically, To add a dictionary to another dictionary in Python, use the update() method. One dictionary is joined to another dictionary using the update() technique. We can add key-value pairs from one dictionary to the other dictionary using this technique.

Let’s understand it by taking an example:

Example

# creating the dictionary named student having multiple key-value pairs.
student = { 'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76 }


# printing the student dictionary before updating it
print( f'''value of the student dictionary before adding new key-value pair: 
{student}
''' )


# new key-value pairs
new_key_value = { 'grade': 'A', 'subject': 'DSA', 'batch': 'E4', 'semester': 4 }


# updating the student dictionary
student.update( new_key_value )


# printing the student dictionary after updating it
print( f'''value of the student dictionary after adding new key-value pair: 
{student}
''' )

Output

value of the student dictionary before adding new key-value pair: 
{'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76}


value of the student dictionary after adding new key-value pair: 
{'name': 'xyz', 'rollNo': '45sc2020', 'age': 22, 'cgpa': 9.76, 'grade': 'A', 'subject': 'DSA', 'batch': 'E4', 'semester': 4}

In the above example, we have the dictionary student. Then we created a dictionary. By using the update method we can add all key-value pairs to the student dictionary.

Example

# creating the dictionary named person having multiple key-value pairs.
person = { 'name': 'xyz', 'city': 'jaipur', 'age': 33 }


# printing the student dictionary before updating it
print( f'''value of the person dictionary before adding new key-value pair: 
{person}
''' )


# new key-value pairs
new_key_value = { 'salary': 50000, 'category': 'gen', 'Date of birth': '15-11-2002' }


# updating the person dictionary
person.update( new_key_value )


# printing the person dictionary after updating it
print( f'''value of the person dictionary after adding new key-value pair: 
{person}
''' )

Output

value of the person dictionary before adding new key-value pair: 
{'name': 'xyz', 'city': 'jaipur', 'age': 33}


value of the person dictionary after adding new key-value pair: 
{'name': 'xyz', 'city': 'jaipur', 'age': 33, 'salary': 50000, 'category': 'gen', 'Date of birth': '15-11-2002'}

Conclusion

With the goal of "Append key value to dictionary python", we have made a few important assumptions in this post. In particular, the term "values" in our title refers to the value in the key/value pairing of a dictionary entry and our definition of "appending" generally means to add.

Therefore, we haven't focused on key addition alone.

We have shown that adding values to an existing dictionary can be done in a number of different ways. Because dictionaries can include a variety of data types and the append() and extend() methods both require the related items to be in a list, they are only marginally useful. The update() function fixes this issue, but users should take caution because it automatically populates existing data rather than adding to them.

Despite being the simplest, the square brackets method appears to be the most flexible because it enables us to add, update, and append values.


Related Topics

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively. Typically, the body of a...

3 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

Python next() function

Python next() function The next() function in Python retrieves the next item from the iterator.  Syntax next(iterator[, default]) Parameter iterable: It is a required parameter which represents an iterable object. default: This parameter represents a default value to...

1 minute read.

Array to String in Python

What is an Array: The idea behind an array is to group several items of the same type, making it easier to locate each element by adding an extra offset to...

4 minutes read.

Python Statistical Module

Python Statistical Module The Python statistical module provides various functions that we can use in our Python program, to perform mathematical statistics operations on the numerical data given to us. The...

8 minutes read.

Python IDE

What is an IDE?  An IDE or an Integrated Development Environment is a type of software where developers can develop many software’s and applications and run the programs inside it. An...

11 minutes read.

How to check the version of the Python Interpreter?

As we all know what an interpreter is, and how important it is. We should also be aware of the fact that it is important to have knowledge of the...

2 minutes read.

Pillow Python introduction and setup

Introduction Advanced image processing implies handling the picture carefully with the assistance of a PC. Utilizing picture handling we can perform activities like upgrading the picture, obscuring the picture, separating text...

4 minutes read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Writing to Excel using Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Spyder (32-bit) - Free download

Spyder is a free and open-source scientific environment created by and for Python engineers, scientists, and data analysts. It is a robust scientific environment created in Python by and for...

3 minutes read.

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

Length of Tuple in Python

What is Tuple? Python is a data structure in a python programming language; it is the collection of the objects in a sequence. The tuples are immutable; that is, we cannot...

3 minutes read.

Python email utils

Python is a popular programming language in this growing world. There are many resources to learn python online without spending a single penny. In this article, we will talk about a...

4 minutes read.

Python pow() Function

Python pow() Function The pow() function in Python return the parameter ‘x’ to the power ‘y’ and if the parameter ‘z’ is present, it returns x to the power y, modulo z (computed more efficiently than pow(x, y) % z). Syntax pow(x, y[, z]) Parameter x: This parameter represents the base...

1 minute read.

Python List extend() method

Python List extend() method The list.extend() method extends the list by appending all the items from the iterable. Syntax list.extend(iterable) Parameter iterable: It is a required parameter which represents any iterable unlike list, set, tuple, etc. Example 1 # Python...

1 minute read.

Assignment Operators in Python

The prime usage of Assignment Operators is to assign values to variables. These are taken into account to do operations on values and variables. There are some special symbols in python...

4 minutes read.

Data Class in Python

Introduction In Python 3.7, the dataclass modules are introduced as a practical tool for creating organized classes designed specifically for data storage. These classes contain specific attributes and capabilities to deal...

6 minutes read.

Python vs PHP

Python Python is a high-level, object-oriented, interpreted language that is used to create independent program and algorithms for a variety of applications. It has a large library support base. In 1990,...

3 minutes read.

Python Interface

When creating an application, it is important to continuously keep track of its changes. As an application grows, sometimes it gets hard to manage its updates and changes. Often, you...

4 minutes read.