Dictionaries

45 min read Dictionaries and Python Modules

This is a free course. Log in to run the code exercises and track your progress.

Dictionaries

A dictionary maps keys to values. It is written in curly brackets with key: value pairs. Keys must be unique and immutable (numbers, strings, tuples); values can be anything. Dictionaries are mutable.

marks = {"Asha": 88, "Ravi": 92}
print(marks["Ravi"])     # 92: access by key, not by position
marks["Meera"] = 79      # add a new pair
marks["Asha"] = 90       # modify an existing value
del marks["Ravi"]        # remove a pair
print("Ravi" in marks)   # False: `in` checks the keys
for name in marks:       # traversal visits the keys
    print(name, marks[name])

Counting with a dictionary needs only one pass over the data. get(key, 0) gives 0 the first time a key is seen instead of raising a KeyError:

freq = {}
for ch in "banana":
    freq[ch] = freq.get(ch, 0) + 1
print(freq)   # {'b': 1, 'a': 3, 'n': 2}

Since Python 3.7 a dictionary remembers the order in which keys were inserted.

Python exercise

Read a string and print the frequency of every character except spaces, as char:count pairs separated by spaces, in order of first appearance. Use a dictionary.

text = input()
freq = {}
for ch in text:
    pass  # skip spaces; add 1 to freq[ch]
print(" ".join(f"{k}:{v}" for k, v in freq.items()))

Log in to edit and run this code.