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.
- By using the [] operator
- 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.