Learn Python Programming  /  Data Structures  /  Dictionary

Dictionary

A dictionary stores data as key-value pairs, giving you fast lookups by a meaningful label instead of a numeric position — Python's equivalent of R's named list.

Creating a Dictionary

R Code
student = {
    "name": "Meera",
    "age": 23,
    "passed": True
}

print(student)
Output
{'name': 'Meera', 'age': 23, 'passed': True}

Accessing and Adding Values

R Code
print(student["name"])        # raises KeyError if missing
print(student.get("grade"))  # safer: returns None instead of an error
print(student.get("grade", "N/A"))  # or provide your own default

student["grade"] = "A"   # add a new key
student["age"] = 24     # update an existing key
print(student)
Output
Meera
None
N/A
{'name': 'Meera', 'age': 24, 'passed': True, 'grade': 'A'}
💡 Tip
Prefer .get(key, default) over square brackets whenever a key might not exist - it avoids crashing your program with a KeyError.

Looping Over a Dictionary

R Code
scores = {"Math": 90, "Physics": 85, "Biology": 78}

for subject, score in scores.items():
    print(subject, ":", score)
Output
Math : 90
Physics : 85
Biology : 78

Removing a Key

R Code
student.pop("passed")   # removes and returns the value
del student["grade"]   # removes without returning it
print(student)
Output
{'name': 'Meera', 'age': 24}

Nested Dictionaries

R Code
company = {
    "name": "DataCorp",
    "ceo": {"name": "Zayn", "age": 41}
}

print(company["ceo"]["name"])
Output
Zayn

Advanced: Dictionary Comprehension

🚀 Advanced Example
Just like list comprehensions, dictionary comprehensions build a new dictionary in one line.
R Code
nums = [1, 2, 3, 4, 5]
squares = {n: n**2 for n in nums}
print(squares)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Key Points

  • A dictionary stores key-value pairs and gives fast lookup by key.
  • Use .get(key, default) instead of square brackets to avoid KeyError on a missing key.
  • Loop with .items() to get both the key and value together.
  • A dictionary comprehension {k: v for ...} builds a new dictionary in one line.