⚡0 XP🔥0

Dictionaries

Lesson 18 of 33 ⏱ 6 min read ✎ 4 exercises ❓ 5-question quiz ▶ Runs Python

Store data as key-value pairs - create, read, update and delete entries, loop over dictionaries, use get(), nested dictionaries and counting patterns.

What is a dictionary?#

A dictionary (dict) stores data as key: value pairs. Instead of finding items by position (like lists), you find them by a meaningful key.

student = {
    "name": "Asha",
    "age": 20,
    "course": "Python",
    "marks": [85, 90, 78],
}

Think of a real dictionary: you look up a word (key) to get its meaning (value). Or a phone contact list: name → number.

हिंदी में समझें

Dictionary में data "key : value" जोड़ियों में रखा जाता है - जैसे फ़ोन की contact list में नाम → नंबर।

List में आप किसी चीज़ तक उसकी position (0, 1, 2...) से पहुँचते हैं, लेकिन dictionary में उसके नाम (key) से - जैसे student["name"]। यह ज़्यादा समझने में आसान है, क्योंकि आपको याद नहीं रखना पड़ता कि name किस position पर था।

Keys unique होती हैं (एक ही key दो बार नहीं हो सकती) और immutable होनी चाहिए (string, number, tuple)। Values कुछ भी हो सकती हैं - list, दूसरी dictionary, कुछ भी।

Properties:

  • Keys are unique - a repeated key overwrites the old value.
  • Keys must be immutable: strings, numbers, tuples.
  • Values can be anything - numbers, lists, other dicts.
  • Dictionaries keep insertion order (Python 3.7+) and are mutable.

Accessing values#

▶ Try it YourselfPython
Ctrl + Enter to run
Common Mistake

student["city"] raises KeyError: 'city' when the key doesn't exist. Use .get() when a key might be missing, or check with if "city" in student: first.

Adding and updating#

The same syntax adds a new key or updates an existing one:

▶ Try it YourselfPython
Ctrl + Enter to run

Removing#

Code What it does
del d[key] delete a key (KeyError if missing)
d.pop(key) remove and return its value
d.pop(key, default) same, but no error if missing
d.popitem() remove and return the last inserted pair
d.clear() empty the dictionary
▶ Try it YourselfPython
Ctrl + Enter to run

Looping over a dictionary#

▶ Try it YourselfPython
Ctrl + Enter to run

keys(), values(), items()#

marks.keys()     # dict_keys(['Maths', 'Science', 'English'])
marks.values()   # dict_values([92, 85, 78])
marks.items()    # dict_items([('Maths', 92), ('Science', 85), ('English', 78)])

Wrap them in list() if you need an actual list.

Checking keys#

if "Maths" in marks:        # checks KEYS, not values
    print("Maths marks found")
if 92 in marks.values():    # check values explicitly
    print("Someone got 92")

Counting with a dictionary - a very common pattern#

▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

count[v] = count.get(v, 0) + 1 - इस लाइन को ध्यान से समझें, यह बहुत काम आती है:

  1. count.get(v, 0) - अगर v पहले से dictionary में है तो उसकी गिनती दो, वरना 0 दो।
  2. उसमें + 1 जोड़ो।
  3. नई गिनती वापस count[v] में रख दो।

यानी पहली बार कोई चीज़ मिली तो गिनती 1 हो जाएगी, दूसरी बार 2, और ऐसे ही आगे।

Tip

Python also has collections.Counter which does this in one line: Counter(votes). You'll meet it in the Modules lesson.

Nested dictionaries#

Real data (like JSON from websites and APIs) is usually nested:

▶ Try it YourselfPython
Ctrl + Enter to run

List of dictionaries - a table of records#

▶ Try it YourselfPython
Ctrl + Enter to run

(lambda is explained in the Lambda lesson - here it just tells sorted to compare by salary.)

Other ways to create dictionaries#

d1 = dict(name="Ravi", age=21)
d2 = dict(zip(["a", "b", "c"], [1, 2, 3]))      # {'a': 1, 'b': 2, 'c': 3}
d3 = dict.fromkeys(["x", "y"], 0)               # {'x': 0, 'y': 0}
squares = {n: n * n for n in range(1, 6)}       # dict comprehension
merged = d1 | {"city": "Indore"}                # merge (Python 3.9+)

Dictionary methods - quick reference#

Method Purpose
get(k, default) safe read
keys(), values(), items() views for looping
update(other) add/overwrite many pairs
pop(k[, default]) remove and return a value
popitem() remove last pair
setdefault(k, v) get k; if missing, insert k with v
copy() shallow copy
clear() remove all

Summary#

  • Dictionaries map unique, immutable keys to values: {"key": value}.
  • Read with d[key] (KeyError if missing) or d.get(key, default).
  • d[key] = value adds or updates; del, pop remove.
  • Loop with .keys(), .values(), .items().
  • d.get(k, 0) + 1 is the standard counting pattern; nested dicts model real-world data.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Student record

Create a dictionary student with keys name → "Karan", age → 20, course → "Python". Then change age to 21, add a key city → "Indore", and print the dictionary.

Expected output:
{'name': 'Karan', 'age': 21, 'course': 'Python', 'city': 'Indore'}
2

Word frequency

Read a sentence and build a dictionary freq that counts how many times each word appears (lower case). Print the words and counts in alphabetical order, one per line, as word: count.

Test input:
the cat and the dog and the bird
Expected output:
and: 2
bird: 1
cat: 1
dog: 1
the: 3
3

Price lookup

Read an item name. If it exists in prices, print <item>: Rs. <price>, otherwise print <item> not available.

Test input:
tea
Expected output:
tea: Rs. 15
4

Topper

Print the name of the student with the highest marks in results, and their marks, like Neha 94.

Expected output:
Neha 94

Quick Quiz

Q1.

If d = {"a": 1}, what does d["b"] do?

Q2.

What does d.get("x", 0) return if "x" is not in d?

Q3.

Which can NOT be a dictionary key?

Q4.

What happens with d = {"a": 1, "a": 2}?

Q5.

Which loop gives both key and value?