DEV Community

Cover image for Dictionaries in Python.
Keshav Jindal
Keshav Jindal

Posted on

Dictionaries in Python.

1. What are dictionaries in Python

  • Dictionary is one of the data types which is used to store data in the pairs of key : data.

  • It is ordered.

  • It is mutable.

  • Keys should not be duplicated but data can be same.

  • Dictionaries are written with curly brackets.

2. Creating a Dictionary

  1. It is encloses in curly {} braces.
  2. Separated by a comma (,).
  3. It holds values in pairs of keys corresponding with data.
  4. Keys cannot be repeated and are immutable.
  5. Data can be of any Datatype.

2.1 Example

dict = {1: 'A', 2: 'B', 3: 'C'}
print(dict)
Enter fullscreen mode Exit fullscreen mode

OUTPUT
{1: 'A', 2: 'B', 3: 'C'}

3. Accessing data of a dictionary
We can access the data by their respective keys.
3.1 Syntax

dict = {1: 'A', 2: 'B', 3: 'C'}
print(dict[1])
Enter fullscreen mode Exit fullscreen mode

OUTPUT
A
4. Adding elements to a dictionary
Syntax:

dict = {1: 'A', 2: 'B', 3: 'C'}
print("old dictionary")
print(dict)
new_dict=dict[4]='a'
print("Updated dictionary")
print(dict)
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
old dictionary
{1: 'A', 2: 'B', 3: 'C'}
Updated dictionary
{1: 'A', 2: 'B', 3: 'C', 4: 'a'}

Oldest comments (0)