MyInternships.in

Python Data Structures

Python Dictionaries

A dictionary stores data as key-value pairs, letting you look up a value instantly by its unique key instead of searching by position.


Creating a Dictionary

You create a dictionary with curly braces, writing each key and value separated by a colon. Keys must be unique and immutable, such as a string, number, or tuple.

Creating a dictionary
Python
student = {
    "name": "Aarav",
    "age": 21,
    "course": "B.Tech"
}
print(student)

Accessing Values

Access a value with square-bracket key lookup, or use get(), which returns None (or a default you supply) instead of raising an error when the key is missing.

Accessing values safely
Python
student = {"name": "Aarav", "age": 21}

print(student["name"])          # Aarav
print(student.get("city"))      # None
print(student.get("city", "NA")) # NA

Adding, Updating and Deleting

Assign to a new key to add it, or to an existing key to update its value. del and pop() remove a key — pop() also returns the value that was removed, which is handy inside functions.

Modifying a dictionary
Python
student = {"name": "Aarav", "age": 21}

student["age"] = 22          # update
student["city"] = "Delhi"    # add
del student["city"]          # delete
age = student.pop("age")     # remove and return
print(student, age)

Iterating Over a Dictionary

keys() returns all keys, values() returns all values, and items() returns key-value pairs — items() is the most common choice inside a for loop.

Looping with items()
Python
student = {"name": "Aarav", "age": 21, "course": "B.Tech"}

for key, value in student.items():
    print(key, "->", value)

Why Use a Dictionary?

  • Fast lookup by a meaningful key instead of a numeric index.
  • Modelling real-world records, like a JSON API response or a database row.
  • Counting occurrences, grouping data, or building simple caches.
ℹ️

Since Python 3.7, dictionaries remember insertion order, so looping over them gives keys in the order you added them.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships