×

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 Matrix Multiplication

One of the most fundamental mathematical structures, matrices are used often in many disciplines, including mathematics, physics, engineering, computer science, etc. For example, matrices and associated operations (multiplication and addition) are...

8 minutes read.

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 int()

Python int() class The int() class in Python returns an integer object constructed from a number or string x. Syntax class int(x, base=10) Parameter x: This parameter represents a number or a string that can be converted into...

1 minute read.

Checking whether a String Contains a Set of Characters in python

In this tutorial, we will learn how to examine or check whether a string contains any set of characters or a substring and if it contains, we will learn how...

6 minutes read.

Text detection using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.

How to Parse JSON in Python

JSON The JSON, the Java Script Object Notation, is an open standard file designed for data interchange; it is light-weighted text. The JSON uses human-readable text to store and transmit the...

4 minutes read.

Python Packages

A package is a collection of Python modules that share a similar namespace and are generated by putting all of the modules in a single directory with certain special files...

6 minutes read.

Python program to check if two strings are anagram or not

Python program to check if two strings are anagram or not Problem: This is a python program that takes two strings and checks if given strings are anagram or not. Examples: Input: string1...

1 minute read.

Paramiko Python 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...

6 minutes read.

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal We know that the most widely used number system is a decimal system, but the computer only understands binary values. The...

2 minutes read.

Python md5() function

Python md5() function The md5() function in PHP calculates the md5 hash of a string. Syntax md5 ( string $str [, bool $raw_output] ) Parameter str(required)- This parameter specifies the string. raw_output(optional)- This parameter specifies a hex or binary output format: TRUE - Raw 16 character binary...

1 minute read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Python len() function

Python len() function The len() function in Python  returns the number of items in an object. Syntax len(s) Parameter s: This parameter represents a sequence (such as a string, bytes, tuple, list, or range) or...

1 minute read.

Python Operators

Operators in Python programming An operator is a symbol that operates on one or more operands. An operand is a value or a variable on which we perform the operation....

5 minutes read.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

Classes & Objects in Python

Classes and Objects are used in most modern programming languages, mainly in Object-oriented Programming languages. What is meant by Object Oriented Programming language? Usage of objects and their components in order to...

7 minutes read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

Python Break Statement

In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration,...

2 minutes read.