PythonDictionaries

DICTIONARY

A dictionary is a data type in Python that stores data as key-value pairs. Unlike lists, dictionaries use unique keys to access values instead of indices. Dictionaries can be created using the dict() constructor or curly braces {}.


Characteristics of Dictionaries

  • A dictionary is an unordered set of key-value pairs.
  • Keys are unique and must be immutable (e.g., strings, numbers, tuples).
  • Values are mutable and can be of any data type.
  • Dictionaries are stored internally as mappings.

Examples of Dictionaries

# Creating a dictionary with student names as keys and marks as values
student = {'Raghav': 89, 'Nitya': 91, 'Asif': 88}
print(student)
# Output: {'Raghav': 89, 'Nitya': 91, 'Asif': 88}
 
# Creating an empty dictionary
dict_marks = {}
# Or
dict_marks = dict()
 
# Creating a nested dictionary
student = {'Raghav': {'Eng': 78, 'Maths': 87}, 'Nitya': {'Eng': 78, 'Maths': 87}}
print(student)
# Output: {'Raghav': {'Eng': 78, 'Maths': 87}, 'Nitya': {'Eng': 78, 'Maths': 87}}

Working with Dictionaries

1. Accessing a Value

Values in a dictionary are accessed using their corresponding keys.

student = {'Raghav': 89, 'Nitya': 91, 'Asif': 88}
print(student['Raghav'])  # Output: 89

2. Accessing Keys

The keys() function retrieves all keys from the dictionary.

print(student.keys())  # Output: dict_keys(['Raghav', 'Nitya', 'Asif'])

3. Accessing Values

The values() function retrieves all values from the dictionary.

print(student.values())  # Output: dict_values([89, 91, 88])

4. Accessing Items

The items() function retrieves all key-value pairs as tuples.

print(student.items())  
# Output: dict_items([('Raghav', 89), ('Nitya', 91), ('Asif', 88)])

5. Membership

The in and not in operators check if a key exists in the dictionary.

print('Nitya' in student)  # Output: True
print('Pihu' not in student)  # Output: True

6. Traversing a Dictionary

Traversing a dictionary means iterating over its key-value pairs.

Method 1:

for key in student:
    print(f"Key= {key} and Value= {student[key]}")
# Output:
# Key= Raghav and Value= 89
# Key= Nitya and Value= 91
# Key= Asif and Value= 88

Method 2:

for key, value in student.items():
    print(f"Key= {key} and Value= {value}")
# Output:
# Key= Raghav and Value= 89
# Key= Nitya and Value= 91
# Key= Asif and Value= 88

7. Adding a New Element

New elements can be added to a dictionary using the assignment operator =.

student['Pihu'] = 90
print(student)
# Output: {'Raghav': 89, 'Nitya': 91, 'Asif': 88, 'Pihu': 90}

8. Updating an Existing Element

If a key already exists, its value can be updated.

student['Pihu'] = 94
print(student)
# Output: {'Raghav': 89, 'Nitya': 91, 'Asif': 88, 'Pihu': 94}

9. Deleting an Element

Use the del statement to remove a key-value pair.

del student['Asif']
print(student)
# Output: {'Raghav': 89, 'Nitya': 91}

Note: If a non-existing key is passed, it raises a KeyError.


Key Notes:

  • Keys must be unique and immutable.
  • Values can be mutable and of any data type.
  • Dictionaries are mutable and efficient for lookups.

Try It Yourself

Problem 1: Add and Update a Dictionary

Write a program to create a dictionary of 3 friends’ names and their ages. Add a new friend and update the age of one existing friend.

Show Code
# Creating a dictionary
friends = {'Alice': 25, 'Bob': 27, 'Charlie': 22}
 
# Adding a new friend
friends['Diana'] = 24
 
# Updating an existing friend's age
friends['Alice'] = 26
 
print(friends)
# Output: {'Alice': 26, 'Bob': 27, 'Charlie': 22, 'Diana': 24}

Problem 2: Count Occurrences of Characters

Write a program to count the occurrences of each character in a given string and store the result in a dictionary.

Show Code
text = "hello world"
char_count = {}
 
for char in text:
    if char in char_count:
        char_count[char] += 1
    else:
        char_count[char] = 1
 
print(char_count)
# Output: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

Pyground

Play with Python!

Output: