×

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

Python Subprocess Call Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Python Hash Table

An Introduction to Hashing A technique which used to identify a particular object uniquely from a set of similar objects is known as Hashing. Some real-life examples of hashing implementations include: A...

9 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

Iterate through the list in Python

One of the six basic data types of the Python computer language is the list. You must be familiar with the methods and functions that deal with lists in order...

7 minutes read.

Working with files 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 an...

5 minutes read.

Python String Variable

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

4 minutes read.

Operator Overloading in Python

In any programming language, + is an arithmetic operator; it adds two numbers to give the sum. Have you ever tried to concatenate two strings? Concatenating two strings is adding...

5 minutes read.

Create Table Using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With this library's...

4 minutes read.

How to append a string in python

Adding or appending a string to another string is easy in Python. It is called concatenation and is a basic concept of strings in almost all programming languages. Ways to Append...

4 minutes read.

Python program to sort the array element into ascending order

Python program to sort the array element into ascending order In this example, we'll see how to sort the array elements in ascending order using a Python program. Sorting is a...

2 minutes read.

Python program to add two number

Python program to add two number This program will add the two numbers and display their sum on the screen. Example: Input: Number1 = 20        Number2 = 30   Output: Sum =...

2 minutes read.

Fsolve in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Dictionary to JSON Python

In python JSON (JavascriptObject Notation). In the programming language, the text file is made using the script file.We can use many built-in packages which arenamedJSON.Before using the packages, we have...

3 minutes read.

Python Dictionary pop() method

Python Dictionary pop() method The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key. Syntax dictionary.pop(key[, default]) Parameter key – This argument signifies the key which is to...

2 minutes read.

Python input() function

Python input() function The input() function in Python reads a line from input and converts it to a string (stripping a trailing newline). Syntax input([prompt]) Parameter prompt: This function represents a string, depicting a default...

1 minute read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Python Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data...

4 minutes read.

Python Letter to Number

Python Letter to Number In this tutorial, we will convert the given letters into numbers using a Python. We will convert the given letter into the letter value as defined in...

3 minutes read.