×

Add a key-value pair to dictionary in Python

In programming, data type defines the type of value that a variable can hold. With help of these, we can perform various mathematical, logical, or relational operations on that particular variable. Similarly, Dictionary is also a data type in the programming language.

What is a Dictionary?

It is a collection of unordered data. Unlike other data types, it does not hold a single value as its element, it holds elements in the format of key-value pair, where keys and values are separated by ‘:’ and two keys are separated by a comma. A dictionary can have identical values but it cannot store identical keys. While creating a dictionary we should keep in mind that keys are case sensitive i.e., both ‘day’ and ‘Day’ will be considered as different keys as the first letter of both words is in a different case (small letter and capital letter).

How to create a Dictionary?

# Creating a Dictionary  
dic1={1: 'One', 2: 'Two', 3: 'Three'} 
print("\nDictionary with the use of Integer Keys: ") 
print(dic1) 
    
# Creating a Dictionary with different keys
dic1={'name': 'Amit', 1: [08, 01, 20, 04]} 
print("\nDictionaryusingdifferent Keys: ") 
print(dic1) 
    
# Creating a Dictionary using the dict() method 
new=dict({11: 'Eleven', 12: 'Twelve', 13:'Thirteen'}) 
print("\nDictionaryusingdict() function: ") 
print(new) 
    
# Creating a Dictionary with each item as a Pair 
new1=dict([(20, 'Twenty'), (22, 'Twenty-Two')]) 
print("\nDictionaryusing paired items: ") 
print(new1) 

Output:

Add a key:value pair to dictionary in Python

What are keys in a Dictionary?

As we know, a dictionary holds the data in the form of key-value pair, and between every key-value pair, there rests a colon “:”, and these pairs are divided by commas “,”.

Keys are unique whereas values can be the same in a dictionary. In a dictionary, it is compulsory that, the keys should be of immutable data type, but values can be of any type.

Properties of keys in a Dictionary

  • Duplicate keys are not allowed, as keys have to be unique. In this case, if same keys are entered, then the key entered at last is considered.

For example:

dict={'Name':'Aadi','Age':18,'Blood_Group' :'A+', 'Name':'Amit'}
print("dict['Name']: ",dict['Name'])

Output:

Add a key:value pair to dictionary in Python

As we can see in this example when we entered multiple keys with the same name, then the key entered at last is considered and when we executed the program, we have received output as “Amit”.

  • Declared keys has to be immutable, i.e., for declaring keys, strings, numbers, or tuples can be used but other methods cannot be used. For example:
dict = {['Name']: 'Zara', 'Blood_Group' : 'A+', 'Age': 7}
print ("dict['Name']: ", dict['Name'])

After executing the above code we get the following output:

Add a key:value pair to dictionary in Python

Unlike keys, values in dictionaries have no hard and fast rules. They can be any user-defined objects, standard objects, or arbitrary objects.

Difference between updating and adding a new key-value pair in a Dictionary:

  • While updating a dictionary, the value of the pre-existing key is updated, no new element is added or deleted and the size of the dictionary remains the same. A dictionary can be updated in two ways:

Method 1:

It can be updated using the update function.

For example:

-	# A program in python to update a dictionary using an update 
-	function 
-	# Dictionary with three items
-	dict1={'X': 'Good', 'y': 'Day',}
-	dict2={'Y': 'Morning'}
-	 
-	# Dictionary before updating
-	print("Dictionary before updating:")
-	print(dict1)
-	 
-	# Updating the value of key 'Y'
-	dict1.update(dict2)
-	print("Dictionary after updating:")
-	print(dict1)

Output:

Add a key:value pair to dictionary in Python

Method 2:

 The value of existing can also be updated directly.

For example:

-	defchkKy(dict, key):
-	    ifkey indict.keys():
-	        dict['a'] = 550
-	    else:
-	        print("Key does not exist in the dictionary.")
-	dict={'a': 600, 'b':50, 'c':400}
-	print("Dictionary before updating:\n", dict)
-	
-	key ='a'
-	chkKy(dict, key)
-	print("Dictionary after updating:\n", dict)

Output:

Add a key:value pair to dictionary in Python
  • While adding a new key-value pair to a dictionary, single or multiple new pairs are added and therefore the size of the dictionary also changes.

For example:

•	dict={'Name':'Zaid','Age':17,'Class':'Elevents'}
•	print("Dictionary before adding new elements: \n",dict)
•	# Add new key-value pairs
•	dict['School']="DAV Public School"
•	dict['Blood Group']="O-"
•	dict['Date of Birth']="5 June 2000"
•	print("\nDictionary after adding new elements: \n",dict)

Output:

Add a key:value pair to dictionary in Python

Some built-in Dictionary Methods and Functions

Some of the Built-in methods are:

                     MethodsDescription
dict.clear()This method deletes all the elements from the dictionary dict.
dict.copy()This method gives back a shallow copy of the dictionary dict.
dict.formkeys()This method creates a new dictionary using keys from seq and values set to value.
dict.get(key, default = None)This method returns the value of the entered key or returns default if the key is not present in the dictionary.
dict.has_key(key)This method is used to check whether a key is present in a dictionary or not.
dict.items()This method is used to return the list of the dictionary’s (key-value) tuple pairs.
dict.keys()This method is used to return the list of keys present in a dictionary.
dict.values()This method is used to return the list of values present in a dictionary.
dict.update(dictn)This method is used to add other dictionary elements to the first dictionary.
dict.setdefault(key, default = None)This method is similar to the “dict.get()” method, but it sets “dict[key] = default” if the key is not present in the dictionary.

Some of the built-in dictionary functions are:

Functions               Description 
cmp(d1, d2)This function is used to compare two dictionaries.
len(dict)This function is used to return the total length of the dictionary, i.e., the total no of items present in it.
str(dict)This function is used to produce a printable representation of a dictionary.
type(variable)This function is used to check the type of the variable passed in this function.

Related Topics

Python Decorator

Python Decorator: A Decorator is an interesting feature of Python that helps the user design patterns and insert a new functionality to an existing object without making any modifications in...

6 minutes read.

Not supported between instances of str and int in python

In this article, you are going to learn why the type error occurs between instances of string and integer datatypes. Also, you will know what kind of error is the...

6 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Notepad++ For Python

In this article, you are going to learn what notepad++ is and how it is integrated with python to use the python programming language. You can also learn how to...

4 minutes read.

Implementing geometric shapes into the game in python

Geometric Drawings We are trying to draw various shapes of geometry by using pygame module to implement Geometric Drawings in game. Let us revise few syntax of basic shapes, to get started...

7 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

Reading a File Line by Line in Python

Introduction In this tutorial, we will learn about reading files in python line by line. Before reading the files, let us know a little information about the files first. Files A file is...

6 minutes read.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.

Exponentiation in Python

What is an Exponent in Python? Exponent is a fundamental mathematical concept that is used in many different areas, such as engineering, physics, and finance. In mathematics, an exponent is a...

4 minutes read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

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.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Find whether the given stringnumber is palindrome or not

Problem statement Sam is found of playing with strings. One day he thought of finding whether a string is a palindrome or not. He wanted to develop a computer process to...

2 minutes read.

Python Dictionary get() method

Python Dictionary get() method The dictionary.get() method returns the value of the item with the specified key. Syntax dictionary.get(keyname, value) Parameter keyname- This parameter represents the key to be searched in the dictionary. value- The parameter...

1 minute read.

Rank Based Percentile GUI Calculator using Tkinter in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

3 minutes read.

Python PyMOTW

The cmd module comprises one class of the general public, Cmd, meant for command processors such interactive shells and other command interpreters as a foundation class. It utilises readline as...

3 minutes read.

How to run Python code from the command prompt

The Windows operating system's command-line interpreter is CMD or Command Prompt. The "MS-DOS Prompt" is comparable to Command.com, used in DOS and Windows 9x computers. It is similar to Unix...

3 minutes read.

Python range() function

Python range() function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Syntax range(stop)        or range(start, stop[, step]) Parameter start: It is...

1 minute read.

Python Prime factorization

Python Prime factorization In this tutorial, we will design a program where we will find all the prime factors of a number. Then, we will print all these prime factors of...

3 minutes read.