Javatpoint Logo
Javatpoint Logo

Python Dictionary

An effective data structure for storing data in Python is dictionaries, in which can simulate the real-life data arrangement where some specific value exists for some particular key.

  • Python Dictionary is used to store the data in a key-value pair format.
  • It is the mutable data-structure.
  • The elements Keys and values is employed to create the dictionary.
  • Keys must consist of just one element.
  • Value can be any type such as list, tuple, integer, etc.

In other words, we can say that a dictionary is the collection of key-value pairs where the value can be of any Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple. Dictionary entries are ordered as of Python version 3.7. In Python 3.6 and before, dictionaries are generally unordered.

Creating the Dictionary

The simplest approach to create a Python dictionary is by using curly brackets {}, but there are other methods as well. The dictionary can be created by using multiple key-value pairs enclosed with the curly brackets {}, and each key is separated from its value by the colon (:). The syntax to define the dictionary is given below.

Syntax:

In the above dictionary Dict, The keys Name and Age are the strings which comes under the category of an immutable object.

Let's see an example to create a dictionary and print its content.

Code

Output

<class 'dict'>
printing Employee data .... 
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}

Python provides the built-in function dict() method which is also used to create the dictionary.

The empty curly braces {} is used to create empty dictionary.

Code

Output

Empty Dictionary: 
{}

Create Dictionary by using  dict(): 
{1: 'Microsoft', 2: 'Google', 3: 'Facebook'}

Dictionary with each item as a pair: 
{4: 'Praneeth', 2: 'Varma'}

Accessing the dictionary values

We've discussed about using indexing to access data stored in lists and tuples. However, because the dictionary's keys are distinct from one another, it is possible to get the values by utilising the keys. The dictionary values can be accessed in the following way.

Code

Output

<class 'dict'>
printing Employee data .... 
Name : David
Age : 30
Salary : 55000
Company : GOOGLE

Python provides us with an alternative to use the get() method to access the dictionary values. It would give the same result as given by the indexing.

Adding Dictionary Values

The dictionary is a mutable data type, and its values can be updated by using the specific keys. The value can be updated along with key Dict[key] = value. The update() method is also used to update an existing value.

Note: If the key-value already present in the dictionary, the value gets updated. Otherwise, the new keys added in the dictionary.

Let's see an example to update the dictionary values.

Example - 1:

Code

Output

Empty Dictionary: 
{}

Dictionary after adding 3 elements: 
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements: 
{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value: 
{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

Example - 2:

Code

Output

<class 'dict'>
printing Employee data .... 
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'GOOGLE'}
Enter the details of the new employee....
Name: Rahul
Age: 28
Salary: 36000
Company:Microsoft
printing the new data
{'Name': 'Rahul', 'Age': 28, 'salary': 36000, 'Company': 'Microsoft'}

Deleting Elements using del Keyword

The items of the dictionary can be deleted by using the del keyword as given below.

Code

Output

<class 'dict'>
printing Employee data .... 
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'GOOGLE'}
Deleting some of the employee data
printing the modified information 
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again 
NameError: name 'Employee' is not defined

The last print statement in the above code, it raised an error because we tried to print the Employee dictionary that already deleted.

Deleting Elements using pop() Method

The pop() method accepts the key as an argument and remove the associated value. Consider the following example.

Code

Output

{1: 'JavaTpoint', 3: 'Website'}

Python also provides a built-in methods popitem() and clear() method for remove elements from the dictionary. The popitem() removes the arbitrary element from a dictionary, whereas the clear() method removes all elements to the whole dictionary.

Iterating Dictionary

A dictionary can be iterated using for loop as given below.

Example 1

Code

Output

Name
Age
salary
Company

Example 2

Code

Output

John
29
25000
GOOGLE

Example - 3

Code

Output

John
29
25000
GOOGLE

Example 4

Code

Output

('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')

Properties of Dictionary Keys

1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value for a single key, then the value which is last assigned is considered as the value of the key.

Consider the following example.

Code

Output

Name John
Age 29
Salary 25000
Company GOOGLE
In [ ]:

2. In python, the key cannot be any mutable object. We can use numbers, strings, or tuples as the key, but we cannot use any mutable object like the list as the key in the dictionary.

Consider the following example.

Code

Output

Traceback (most recent call last):
  File "dictionary.py", line 1, in 
    Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list'

Built-in Dictionary Functions

A technique that may be used on a construct to produce a value is known as a function. Additionally, it doesn't change the construct. A Python dictionary can be used with a handful of the methods that Python provides.

The built-in python dictionary methods along with the description are given below.

  • len()

Python's len() method returns the dictionary's length. Each key-value pair lengthens the string by one.

Code

Output

4
  • any()

The any() method returns True indeed if one dictionary key does have a Boolean expression of True, much like it does for lists and tuples.

Code

Output

True
  • all()

Unlike in any() method, all() only returns True if each of the dictionary's keys contain a True Boolean value.

Code

Output

False
  • sorted()

The sorted() method returns an ordered series of the dictionary's keys, much like it does with lists as well as tuples. The initial Python dictionary is not changed by the ascending sorting.

Code

Output

[ 1, 5, 7, 8]

Built-in Dictionary methods

The built-in python dictionary methods along with the description and Code are given below.

  • clear()

It is used to delete all the items of the dictionary.

Code

Output

{ }
  • copy()

It returns a shallow copy of the dictionary.

Code

Output

{1: 'Microsoft', 2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
  • pop()

eliminates the element using the defined key.

Code

Output

{2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

popitem()

removes the most recent key-value pair entered

Code

Output

{1: 'Microsoft', 2: 'Google', 3: 'Facebook'}
  • keys()

It returns all the keys of the dictionary.

Code

Output

dict_keys([1, 2, 3, 4, 5])
  • items()

It returns all the key-value pairs as a tuple.

Code

Output

dict_items([(1, 'Microsoft'), (2, 'Google'), (3, 'Facebook'), (4, 'Amazon'), (5, 'Flipkart')])
  • get()

It is used to get the value specified for the passed key.

Code

Output

Facebook
  • update()

It updates the dictionary by adding the key-value pair of dict2 to this dictionary.

Code

Output

{1: 'Microsoft', 2: 'Google', 3: 'TCS'}
  • values()

It returns all the values of the dictionary.

Code

Output

dict_values(['Microsoft', 'Google', 'TCS'])

Built-in Dictionary methods

The built-in python dictionary methods along with the description are given below.

SN Method Description
1 dic.clear() It is used to delete all the items of the dictionary.
2 dict.copy() It returns a shallow copy of the dictionary.
3 dict.fromkeys(iterable, value = None, /) Create a new dictionary from the iterable with the values equal to value.
4 dict.get(key, default = "None") It is used to get the value specified for the passed key.
5 dict.has_key(key) It returns true if the dictionary contains the specified key.
6 dict.items() It returns all the key-value pairs as a tuple.
7 dict.keys() It returns all the keys of the dictionary.
8 dict.setdefault(key,default= "None") It is used to set the key to the default value if the key is not specified in the dictionary
9 dict.update(dict2) It updates the dictionary by adding the key-value pair of dict2 to this dictionary.
10 dict.values() It returns all the values of the dictionary.
11 len()
12 popItem()
13 pop()
14 count()
15 index()

Next TopicPython Functions





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA