The data type dictionary falls under mapping. 

  • It is a mapping between a set of keys and a set of values. 
  • The key-value pair is called an item. 
  • A key is separated from its value by a colon(:) and consecutive items are separated by commas. 
  • Items in dictionaries are unordered, so we may not get back the data in the same order in which we had entered the data initially in the dictionary.

Creating a dictionary

  •  To create a dictionary, the items entered are separated by commas and enclosed in curly braces. 
  • Each item is a key value pair, separated through colon (:). 
  • The keys in the dictionary must be unique and should be of any immutable data type, i.e., number, string or tuple. 
  • The values can be repeated and can be of any data type. 

Example:

Creating a Dictionary - Example - Teachoo .png

Accessing items in a dictionary

The items of a dictionary are accessed via the keys rather than via their relative positions or indices. Each key serves as the index and maps to a value.

Example:

Accessing item in a Dictionary - Example - Teachoo.png

Dictionaries are Mutable

Dictionaries are mutable which implies that the contents of the dictionary can be changed after it has been created. 

Adding a new item

Example:

Adding a new item to a Dictionary - Example - Teachoo.png

Modifying an existing item

The existing dictionary can be modified by just overwriting the key-value pair. 

Example:

Modifying an existing item in a dictionary - Example - Teachoo.png

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.