×

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify, or remove any key value in the dictionary without any duplicate values, causing the dictionary to have to be unique.

There is no defined method to add a new key to the dictionary. If you have to add a new key to the dictionary, we use the assignment operator with the dictionary key.

Appending items in the dictionary using the dict[key] method:

We can add an item to the python dictionary by giving the key and its assigned value. Like this command “dict[key]=value”       

Note: we have to make sure whether the key already exists in the dictionary or else the assignment will auto-update the values. If you know that your program contains duplicate keys, it is better to add a conditional append without directly appending values.

Example

d = {'a': 4, 'b': 6}
print(d)
d['a'] = 10   # existed key got overwrite
d['c'] = 5    # new key is added 
d['d'] = 4
print(d)

Output

{'a': 4, 'b': 6}
{'a': 10, 'b': 6, 'c': 5, 'd': 4}

In this code, we created a dictionary with the name “d” with keys a and b, giving values to it as 4 and 6 by a comma separating each key. Next, we printed the original dictionary and then added a new value, a duplicate value, and printed the dictionary again. Where the new value gets added, and the duplicate values are overwritten.

Here we see that the values got overwritten, so we can use conditional append instead of directly adding values to overcome this. Hence we can also use the if condition to ensure that the dictionary keys are not overwritten.

Appending items in the dictionary using the update() method:

We have another way to append the values to the dictionary using the command update() method. The python dictionary update() method allows us to append a dictionary into another. As this method doesn’t require any conditions to look after the duplicate values, it won’t overwrite any dictionary values.

Example

blog = {'name':'travelling', 'plot':'general'}
print("current dictionary is: ", blog)


# Adding the author details to the dictionary
blog.update({'Author':'siri'})
print("Updated dictionary is: ", blog)


# Appending another dictionary
guests = {'Guest1':'Mayu'}
blog.update(guests)
print("Updated dictionary is: ", blog)

Output:

current dictonary is:  {'name': 'travelling', 'plot': 'general'}


Updated dictionary is:  {'name': 'travelling', 'plot': 'general', 'Author': 'siri'}


Updated dictionary is:  {'name': 'travelling', 'plot': 'general', 'Author': 'siri', 'Guest1': 'Mayu'}

Looking at the above code, we created a dictionary “blog” and added an item to the dictionary. Then we append a new dictionary into another one using the command update() and print the updated dictionary. In this process, there will be no overwriting and no duplicate values.  

A code using the if condition:

Example

d={'a':10,'b': 15, 'c':20}
print(d)
if 'c' not in d.keys():  #appending already existing values
    d['c'] = 30
if 'e' not in d.keys():
    d['e'] = 5
print(d)

Output

{'a': 10, 'b': 15, 'c': 20}
{'a': 10, 'b': 15, 'c': 20, 'e': 5}

As you can see in this code, we created a dictionary ‘d’ with keywords a, b, and c and their assigned values. Then we append some values for c and e with new values assigned to them using the if condition. So as c already existed in the dictionary, the appended value didn’t overwrite because of the if condition. The value of e is added newly to the dictionary. In this way, we can check and add items to the dictionary.

Conclusion

As we can see, we appended the values, changed the values, replaced the duplicates in the dictionary, and modified it into a new one. This way, all the python dictionaries can be changed, added new values, deleted values, changed formats, and printed the altered or modified dictionary.

So, the above codes help us to understand the concepts of adding the item into a python dictionary. We added new values, created duplicate values, and inserted a dictionary into a dictionary.


Related Topics

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.

Reverse a sentence In Python

Introduction The built-in reverse() function is not supported by the Python string library. As we know, a Python string is defined as a set of Unicode characters and Python provides various...

4 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

PyDev with Python IDE

What is IDE? Integrated Development Environment is the abbreviation of IDE. It is a coding tool that automates code editing, finding errors and testing. IDE combines all the developer tools into...

3 minutes read.

Best resources to learn Numpy and Pandas in python

In this tutorial, we will discuss the different resources where we can learn about NumPy and Pandas libraries of Python in a more efficient way. NumPy NumPy, a Python library used for...

4 minutes read.

Python Lexicographic Order

Python lexicographic order Before we discuss the lexicographic order in Python, we should understandwhat is lexicographic order and sort according to lexicographic order. Lexicographic order In mathematics, the generalization of the alphabetical order...

5 minutes read.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.

Python Function

Python Function A Python function is a reusable, organized block of code that is used to perform the specific task. The functions are the appropriate way to divide an extensive program into a...

7 minutes read.

Python pycountry

What is Pycountry? 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...

4 minutes read.

Python Modules

Python Modules The Python module is a collection of definition and statements. It can contain functions, classes, and variables.  Combining the related code into a module makes the code easier to understand and use....

5 minutes read.

Python Call Function

In this article, you will learn about calling a function in Python. But before learning this, we should know about functions in Python.So, let’s get some overview of functions in...

6 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

Speech Recognition in Python

What is Speech Recognition? Speech Recognition is a term defined for automatic recognition of human speech. Speech recognition is the most significant activity in the domain of the interaction between the...

8 minutes read.

How to Open a file in python with Path

In this tutorial, we will see rather than the traditional way of opening a file by locating or navigating it from our desktops; we will learn how to open the...

2 minutes read.

Python issubclass() Function

Python issubclass() Function The issubclass() function in Python returns a boolean value ‘True’ if the given object is a subclass of classinfo, else it returns False. Syntax issubclass(class, classinfo) Parameter class: It is a required parameter which represents a tuple...

1 minute read.

Covariance in Python

Covariance is defined as the estimate of the difference of change between two variables or more variables. It defines the changes of two variables together. In Python, The covariance can...

2 minutes read.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

Assertion error in python

In this article, we will discuss assertions in the python programming language. Assertion: Assertions are a way of telling a program to test a certain condition and trigger an error if the...

3 minutes read.

Exrex Python

Python: 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 faster...

4 minutes read.