DEV Community

Vasanthakumari N
Vasanthakumari N

Posted on

Python Day 28 – Understanding Dictionaries in Python

A dictionary is a collection of key-value pairs. It allows us to store related information together and access values using their keys.

1. What is a Dictionary?

A dictionary is a data structure that stores data in the form of key-value pairs.

Each pair contains:

  • Key: Used to identify or access a value.
  • Value: The data associated with the key.

Example:

d = {"dhoni": 90, "virat": 108}

print(d["dhoni"])

Enter fullscreen mode Exit fullscreen mode
Output:

90
Enter fullscreen mode Exit fullscreen mode

Here:

  • "dhoni" is the key.
  • 90 is the value.
  • "virat" is the key.
  • 108 is the value.

We can access the value directly using its corresponding key.

2. Dictionary Properties

Feature Description
Collection Stores data as key-value pairs
Keys Must be unique
Values Duplicates are allowed
Key Types Must be hashable
Value Types Can be any data type
Mutable Elements can be added, updated, and deleted
Ordered Maintains insertion order (Python 3.7+)
Indexing Does not support positional indexing
Slicing Does not support slicing
Access Values are accessed using keys
Data Structure Also known as an associative array or mapping

3. Dictionary Syntax

A dictionary is created using curly braces {}.

d = {
    "dhoni": 90,
    "virat": 67,
    "rohit": 91
}

print(d)
Enter fullscreen mode Exit fullscreen mode
Output:

{'dhoni': 90, 'virat': 67, 'rohit': 91}
Enter fullscreen mode Exit fullscreen mode

Important points:

  • Keys and values are separated by a colon (:).
  • Each key-value pair is separated by a comma.
  • Curly braces {} are used to create a dictionary.
  • An empty dictionary can be created using {}.

Example:


d = {}

print(type(d))
Enter fullscreen mode Exit fullscreen mode
Output:

<class 'dict'>
Enter fullscreen mode Exit fullscreen mode

4. Keys and Values

Keys

  • Keys must be unique.
  • Keys must be hashable.
  • Strings, numbers, and immutable tuples (containing only hashable elements) can be used as keys.
  • Lists, sets, and dictionaries cannot be used as keys because they are mutable and unhashable.

Values

  • Values can be duplicated.
  • Values can be of any data type.
  • Values can be strings, numbers, lists, tuples, sets, or even dictionaries.

Example:

d = {
    "name": "Dhoni",
    "age": 43,
    "marks": [90, 85, 95],
    "subjects": {"Python", "Java"}
}

print(d)
Enter fullscreen mode Exit fullscreen mode

5. Accessing Dictionary Values

We can access dictionary values using their keys.

scoreboard = {
    "dhoni": 90,
    "virat": 67,
    "rohit": 91
}

print(scoreboard["dhoni"])
print(scoreboard["virat"])
print(scoreboard["rohit"])
Enter fullscreen mode Exit fullscreen mode
Output:

90
67
91
Enter fullscreen mode Exit fullscreen mode

If we try to access a key that does not exist, Python raises a KeyError.

Example:


print(scoreboard["Mohammed"])
Enter fullscreen mode Exit fullscreen mode
Output:

KeyError: 'Mohammed'
Enter fullscreen mode Exit fullscreen mode

We can use the get() method to avoid this error.

print(scoreboard.get("Mohammed"))
Enter fullscreen mode Exit fullscreen mode

Output:

None
Enter fullscreen mode Exit fullscreen mode

6. Adding and Updating Dictionary Elements

Dictionaries are mutable, so we can add new key-value pairs and update existing values.

Adding a new element

scoreboard = {
    "dhoni": 90,
    "virat": 67
}

scoreboard["rohit"] = 91

print(scoreboard)
Enter fullscreen mode Exit fullscreen mode

Output:

{'dhoni': 90, 'virat': 67, 'rohit': 91}
Enter fullscreen mode Exit fullscreen mode

Updating an existing element

scoreboard = {
    "dhoni": 90,
    "virat": 67
}

scoreboard["dhoni"] = 100

print(scoreboard)
Enter fullscreen mode Exit fullscreen mode
Output:

{'dhoni': 100, 'virat': 67}
Enter fullscreen mode Exit fullscreen mode

Remember:

  • If the key already exists, its value gets updated.
  • If the key does not exist, a new key-value pair is added.

7. Dictionary vs Set

Both dictionaries and sets use curly braces, but their purposes are different.

Dictionary
scoreboard = {"dhoni": 90, "virat": 67}

Set
names = {"dhoni", "virat", "rohit"}

Example:


names = {"dhoni", "virat", "rohit"}

print(names["dhoni"])
Enter fullscreen mode Exit fullscreen mode
Output:

TypeError
Enter fullscreen mode Exit fullscreen mode

8. Dictionary with List as a Value

A dictionary can store lists as values.

This is useful when we want to store multiple values for a single key.

Example:

marks_dict = {}

marks_dict["Ramesh"] = [98, 97, 100, 89, 54]
marks_dict["Suresh"] = [58, 67, 90, 89, 54]

print(marks_dict)
Enter fullscreen mode Exit fullscreen mode

Output:

{
    'Ramesh': [98, 97, 100, 89, 54],
    'Suresh': [58, 67, 90, 89, 54]
}
Enter fullscreen mode Exit fullscreen mode

Here:

  • "Ramesh" is a key.
  • [98, 97, 100, 89, 54] is its value.
  • "Suresh" is another key.
  • [58, 67, 90, 89, 54] is its value.

Accessing List Elements Through Dictionary Keys


for mark in marks_dict["Ramesh"]:
    print(mark, end=' ')

Enter fullscreen mode Exit fullscreen mode
Output:

98 97 100 89 54
Enter fullscreen mode Exit fullscreen mode

Here, we first access the list using the dictionary key "Ramesh", and then iterate through the list using a for loop.

A set does not support indexing or accessing elements using keys.

Top comments (0)