📘 CodingMarble Learn

Dictionaries in Python

A dictionary is a mutable collection of key: value pairs written in curly brackets: D = {'Riya': 91, 'Aman': 85}. Values are reached by key (D['Riya']), not by position; a missing key raises KeyError. Keys must be unique and immutable (numbers, strings, tuples); values can be anything. D[key] = value adds a new pair or changes an existing value. Traversal uses for key in D. Useful functions and methods: len(), dict(), keys(), values(), items(), get(), update(), del, clear(), fromkeys(), copy(), pop(), popitem(), setdefault(), max(), min(), count via loops, and sorted(). A classic program counts how many times each character appears in a string.

🎬 Step-by-step story

  1. A dictionary keeps pairs: a key and its value. You find a value by its key, like a word in a real dictionary.
  2. D[key] = value adds a new pair if the key is new. If the key is already there, the value changes.
  3. A for loop goes through the keys one by one. D[k] gives the value of each key.
  4. Methods like keys(), values(), items() and get() help you read the dictionary.
  5. To count letters, go through the word. For each letter, add 1 to its count.
  6. Your turn: type a word and watch the letter counts grow.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

🤔 Common doubts, cleared

Why use keys instead of positions?

Because you remember names, not positions. D['Aman'] is clearer than L[1], and lookup stays fast even for huge dictionaries.

What happens if I add the same key twice?

There is only one locker per key, so the second value replaces the first. Watch Riya's value change from 91 to 95.

Does for k in D give values?

No, it gives keys. Use D[k] or loop over D.items() to get both.

When should I use get() instead of D[k]?

When the key might be missing. get() returns None or your default instead of crashing.

Why check if ch in d before adding 1?

The first time a letter appears it has no count yet, so we set it to 1. Later times we add 1. get(ch, 0) + 1 does both.

Creating a dictionary and accessing by key

D = {'Riya': 91, 'Aman': 85, 'Dev': 78}, E = {}, dict(a=1, b=2).

Access: D['Aman'] → 85. A key that is not there gives KeyError. D.get('Zoya') returns None instead, and D.get('Zoya', 0) returns 0.

Keys must be unique and immutable (int, str, tuple); a list cannot be a key. Membership 'Riya' in D checks keys, not values.

Adding and changing items

D['Zoya'] = 88     # new key → pair added
D['Riya'] = 95     # old key → value changed
del D['Dev']       # remove a pair
D.update({'Aman': 90, 'Ira': 70})

Dictionaries are mutable, and from Python 3.7 they keep the order in which keys were added.

Traversing a dictionary

for k in D:
    print(k, D[k])

for k, v in D.items():
    print(k, '→', v)

Dictionary functions and methods

MethodWhat it does
len(D)number of pairs
D.keys(), D.values(), D.items()all keys / values / (key, value) pairs
D.get(k, default)value of k, or default (no error)
D.update(D2)adds or changes pairs from D2
D.pop(k)removes k and returns its value
D.popitem()removes and returns the last added pair
D.setdefault(k, v)returns D[k]; if k is missing, adds it with v
dict.fromkeys(keys, v)new dict with the given keys all set to v
D.copy(), D.clear()shallow copy / remove all pairs
sorted(D), max(D), min(D)work on the keys

Program: count each character in a string

s = input('Enter text: ')
d = {}
for ch in s:
    if ch in d:
        d[ch] += 1
    else:
        d[ch] = 1
print(d)
# 'banana' → {'b': 1, 'a': 3, 'n': 2}

Shorter: d[ch] = d.get(ch, 0) + 1. The same idea counts words: loop over s.split().

Program: student marks dictionary

n = int(input('How many students? '))
marks = {}
for i in range(n):
    name = input('Name: ')
    marks[name] = int(input('Marks: '))
for name, m in marks.items():
    if m > 75:
        print(name)

Key formulas and definitions

Worked examples

1. D = {'a': 1, 'b': 2}. What are D['b'], len(D), 'a' in D, 1 in D?

2; 2; True; False (in checks keys, and 1 is a value).

2. Output? D = {'x': 5}; D['y'] = 7; D['x'] = 9; print(D)

{'x': 9, 'y': 7}

3. Output? D = {'Riya': 91, 'Aman': 85}; print(D.get('Dev', 'absent'), D.pop('Aman'), D)

absent 85 {'Riya': 91}

4. Count characters in 'hello'.

{'h': 1, 'e': 1, 'l': 2, 'o': 1}

5. Count words in 'to be or not to be'.

d = {} for w in 'to be or not to be'.split(): d[w] = d.get(w, 0) + 1 # {'to': 2, 'be': 2, 'or': 1, 'not': 1}

6. Find the student with the highest marks in {'Riya': 91, 'Aman': 85, 'Dev': 97}.

best = max(D, key=D.get) → 'Dev'. Or loop: keep the name whose value is largest.

Common mistakes

Practice quiz

1. Dictionaries are written in:
2. D = {'a': 1}; D['b'] gives:
3. Which method returns (key, value) pairs?
4. Which can be a dictionary key?
5. D['x'] = 5 when 'x' already exists:

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What is a dictionary in Python?

A mutable collection of unique key: value pairs in curly brackets, where each value is found by its key.

How do you count characters using a dictionary?

Loop over the string and do d[ch] = d.get(ch, 0) + 1 for each character.

What is the difference between a list and a dictionary?

A list is an ordered sequence accessed by integer index; a dictionary maps unique keys to values and is accessed by key.

Where this is taught

CBSE (India)Class 11Computational Thinking and Programming - 1
CBSE (India)Class 11Introduction to Python

Learn first

Learn next

Related lessons

All Computer Science lessons