DICTIONARY

M3-R5.1 · Chapter 5: Sequence Data Types · 7 min read

Python Dictionaries

1. Introduction to Dictionaries

A dictionary in Python is an unordered, mutable collection of key-value pairs.

Each key is unique and maps to a specific value.

Dictionaries are one of the most powerful and widely used data structures in Python.

Key characteristics:

  • Unordered or Ordered –Dictionaries are unordered in Python versions < 3.7 and insertion ordered in Python 3.7+.
  • Mutable – key-value pairs can be added, changed, or removed after creation
  • Keys must be unique – duplicate keys are not allowed
  • Keys must be immutable – strings, numbers, or tuples can be keys; lists cannot
  • Values can be of any data type – integers, strings, lists, tuples, even other dictionaries
  • Accessed by key – not by numeric index like lists or tuples

2. Creating a Dictionary

Syntax:

dictionary_name = {key1: value1, key2: value2, ...}

A dictionary is created by placing key-value pairs inside curly braces {}, separated by commas. Each key and value is separated by a colon (:).

2.1 Examples

# Empty dictionary

my_dict = {}

my_dict = dict()

# Dictionary with integer keys

my_dict = {1: 'apple', 2: 'ball'}

# Dictionary with string keys (most common)

student = {'name': 'Alice', 'age': 21, 'grade': 'A'}

# Mixed key types

my_dict = {'name': 'John', 1: [2, 4, 3]}

# Using dict() constructor

my_dict = dict(name='Alice', age=21)

# Nested dictionary

students = {

    1: {'name': 'Alice', 'age': 21},

    2: {'name': 'Bob',   'age': 22}

}

3. Accessing Dictionary Elements

3.1 Using Keys (Square Bracket Notation)

Dictionary values are accessed using their corresponding keys inside square brackets [].

student = {'name': 'Alice', 'age': 21, 'grade': 'A'}

print(student['name'])    # Alice

print(student['age'])     # 21

# KeyError if key doesn't exist

# print(student['city'])  --> KeyError: 'city'

3.2 Using get() Method

The get() method is safer — it returns None (or a default value) instead of raising a KeyError when a key is not found.

student = {'name': 'Alice', 'age': 21}

print(student.get('name'))          # Alice

print(student.get('city'))          # None

print(student.get('city', 'N/A'))   # N/A  (default value)

3.3 Accessing Nested Dictionaries

students = {

    1: {'name': 'Alice', 'marks': 95},

    2: {'name': 'Bob',   'marks': 88}

}

print(students[1]['name'])    # Alice

print(students[2]['marks'])   # 88

4. Adding and Modifying Elements

Dictionaries are mutable. You can add new key-value pairs or update existing ones using the assignment operator.

student = {'name': 'Alice', 'age': 21}

# Adding a new key-value pair

student['grade'] = 'A'

print(student)    # {'name': 'Alice', 'age': 21, 'grade': 'A'}

# Modifying an existing value

student['age'] = 22

print(student)    # {'name': 'Alice', 'age': 22, 'grade': 'A'}

# Using update() to add/modify multiple entries

student.update({'city': 'Delhi', 'age': 23})

print(student)

5. Deleting Dictionary Elements

Method / Statement

Description

Example

del dict[key]

Removes a specific key-value pair

del student['age']

dict.pop(key)

Removes key and returns its value

student.pop('age')

dict.popitem()

Removes and returns the last inserted pair

student.popitem()

dict.clear()

Removes all key-value pairs (empties the dict)

student.clear()

del dict

Deletes the entire dictionary object

del student

student = {'name': 'Alice', 'age': 21, 'grade': 'A', 'city': 'Delhi'}

del student['city']

print(student)             # {'name': 'Alice', 'age': 21, 'grade': 'A'}

removed = student.pop('grade')

print(removed)             # A

print(student)             # {'name': 'Alice', 'age': 21}

student.clear()

print(student)             # {}

6. Iterating Through a Dictionary

6.1 Iterating Over Keys (default)

student = {'name': 'Alice', 'age': 21, 'grade': 'A'}

for key in student:

    print(key)

# Output: name  age  grade

6.2 Iterating Over Values

for value in student.values():

    print(value)

# Output: Alice  21  A

6.3 Iterating Over Key-Value Pairs

for key, value in student.items():

    print(key, ':', value)

# Output:

# name : Alice

# age  : 21

# grade: A

7. Dictionary Methods

Method

Syntax

Description

keys()

dict.keys()

Returns all keys as a view object

values()

dict.values()

Returns all values as a view object

items()

dict.items()

Returns all key-value pairs as tuples

get()

dict.get(key, default)

Returns value for key; default if not found

update()

dict.update(other_dict)

Adds/updates entries from another dictionary

pop()

dict.pop(key)

Removes and returns value for the key

popitem()

dict.popitem()

Removes and returns last inserted pair

clear()

dict.clear()

Removes all items from the dictionary

copy()

dict.copy()

Returns a shallow copy of the dictionary

fromkeys()

dict.fromkeys(seq, val)

Creates new dict from keys in seq with value val

Examples:

d = {'a': 1, 'b': 2, 'c': 3}

print(d.keys())      # dict_keys(['a', 'b', 'c'])

print(d.values())    # dict_values([1, 2, 3])

print(d.items())     # dict_items([('a',1),('b',2),('c',3)])

# fromkeys()

keys = ['x', 'y', 'z']

new_dict = dict.fromkeys(keys, 0)

print(new_dict)      # {'x': 0, 'y': 0, 'z': 0}

# copy()

d2 = d.copy()

d2['a'] = 99

print(d)             # original unchanged

8. Membership Operators in Dictionary

The in and not in operators check whether a key exists in a dictionary.

student = {'name': 'Alice', 'age': 21, 'grade': 'A'}

print('name'  in student)       # True

print('city'  in student)       # False

print('age'   not in student)   # False

print('phone' not in student)   # True

# Check value existence using values()

print(21 in student.values())   # True

9. Built-in Functions with Dictionaries

Function

Description

Example

Result

len(dict)

Number of key-value pairs

len({'a':1,'b':2})

2

str(dict)

Converts dictionary to string

str({'a':1})

"{'a': 1}"

type(dict)

Returns the type of the object

type({'a':1})

<class 'dict'>

sorted(dict)

Returns sorted list of keys

sorted({'b':2,'a':1})

['a', 'b']

list(dict)

Converts keys to a list

list({'a':1,'b':2})

['a', 'b']

max(dict)

Returns largest key

max({'b':2,'a':1})

'b'

min(dict)

Returns smallest key

min({'b':2,'a':1})

'a'