Dictionaries

A mutable collection of key-value pairs — instead of a position, every value is reached by its own key.

Introduction

A dictionary stores data as key-value pairs, written with curly braces. Keys must be an immutable type (like a string, number, or tuple); values can be anything.

d = {"name": "ByteWise", "grade": 11, "age": 17}
print(d)
{'name': 'ByteWise', 'grade': 11, 'age': 17}

You can also build one with the dict() function:

d = dict(name="ByteWise", grade=11)
print(d)
{'name': 'ByteWise', 'grade': 11}

Accessing Elements

Values are reached by key, not by position — dictionaries aren't ordered sequences, so there's no index to use.

d = {"name": "ByteWise", "grade": 11}
print(d["name"])
ByteWise

Asking for a key that doesn't exist raises a KeyError:

print(d["age"])
KeyError: 'age'

keys(), values(), and items() give you the keys, the values, or both paired together — handy for looping.

d = {"name": "ByteWise", "grade": 11}
for key, value in d.items():
    print(key, "->", value)
name -> ByteWise grade -> 11

Assigning to a new key adds it; assigning to an existing key updates it.

d = {"name": "ByteWise", "grade": 11}
d["age"] = 17      # adds a new key
d["grade"] = 12    # updates an existing key
print(d)
{'name': 'ByteWise', 'grade': 12, 'age': 17}

in checks whether a key exists (not a value) by default:

d = {"name": "ByteWise", "grade": 11}
print("name" in d)
print("ByteWise" in d.values())
True True

Methods

get() is a safer alternative to d[key] — instead of raising an error for a missing key, it returns None, or a fallback value you provide.

d = {"name": "ByteWise"}
print(d.get("age"))
print(d.get("age", "not set"))
None not set

pop() removes a key and returns its value; popitem() removes and returns the last key-value pair as a tuple; clear() empties the dictionary entirely.

d = {"name": "ByteWise", "grade": 11, "age": 17}
print(d.pop("age"))
print(d.popitem())
print(d)
17 ('grade', 11) {'name': 'ByteWise'}

update() merges another dictionary in, overwriting any keys that already exist.

d = {"name": "ByteWise", "grade": 11}
d.update({"grade": 12, "age": 17})
print(d)
{'name': 'ByteWise', 'grade': 12, 'age': 17}

Just like lists, assigning with d2 = d1 doesn't copy anything — both names share the same dictionary. Use copy() for an actual duplicate.

d1 = {"a": 1}
d2 = d1
d3 = d1.copy()

d1["a"] = 99
print(d2)
print(d3)
{'a': 99} {'a': 1}

setdefault() adds a key only if it isn't already there — if it exists, it just returns the current value without changing anything.

d = {"a": 100}
d.setdefault("a", 999)   # 'a' already exists, unchanged
d.setdefault("b", 200)   # 'b' is new, gets added
print(d)
{'a': 100, 'b': 200}