DEV Community

Cover image for Dictionaries in Python.
Keshav Jindal
Keshav Jindal

Posted on

2

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'}

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay