Dictionary

Learn about dictionaries in Python.

Ali Berro

By Ali Berro

15 min read Section
From: Python Fundamentals: From Zero to Hero

Dictionary

A dictionary is a collection of key-value pairs, similar to a hashmap. Dictionaries are mutable which means that elements can be added, modified, and removed. Keys must be immutable and hashable (like strings, numbers, or tuples), while values can be of any type, including mutable types like lists.

Creating a Dictionary

Dictionaries can be created using curly braces {} with key-value pairs separated by colons:

empty_dict = {}
weather = {
"weather": "rainy",
"temp": "-2.0C"
}
print(weather["weather"]) # rainy

Using the dict() Constructor

The dict() constructor can create dictionaries in several ways:

  1. From keyword arguments: Pass key-value pairs as keyword arguments (keys must be valid Python identifiers):
weather = dict(weather="rainy", temp="-2.0C")
print(weather) # {'weather': 'rainy', 'temp': '-2.0C'}
  1. From a list/tuple of pairs: Pass an iterable containing key-value pairs:
# From a list of lists
pairs = [["weather", "rainy"], ["temp", "-2.0C"]]
weather = dict(pairs)
print(weather) # {'weather': 'rainy', 'temp': '-2.0C'}
# From a list of tuples
pairs = [("weather", "rainy"), ("temp", "-2.0C")]
weather = dict(pairs)
print(weather) # {'weather': 'rainy', 'temp': '-2.0C'}
# From a tuple of ranges (creates keys from range values)
ranges = (range(2), range(5, 7))
numbers = dict(ranges)
print(numbers) # {0: 5, 1: 6}
  1. Empty dictionary: Call dict() with no arguments:
empty = dict()
print(empty) # {}
  1. From both list of pairs and keyword arguments: Pass a list of pairs and keyword arguments:
weather = dict(("weather", "rainy"), ("temp", "-2.0C"), weather="rainy", temp="-2.0C", )
print(weather) # {'weather': 'rainy', 'temp': '-2.0C'}

Warning

Dictionary keys must be unique. If the same key is specified multiple times, the last value will overwrite previous values.

Note

Keys must be hashable (immutable) types. Strings, numbers, and tuples (containing hashable elements) can be used as keys, but not lists or other dictionaries.

Accessing Dictionary Elements

There are several ways to access values in a dictionary:

Using Square Brackets

Given a key, its value can be accessed using square brackets d[key]:

weather = {"weather": "rainy", "temp": "-2.0C"}
print(weather["weather"]) # rainy

Warning

Accessing a key that doesn’t exist using square brackets will raise a KeyError:

weather = {"weather": "rainy"}
print(weather["temp"]) # KeyError: 'temp'

Using .get() Method

The .get(key, default=None) method returns the value associated with the given key. If the key is not present, it returns the default value (or None if no default is specified) instead of raising an error:

weather = {"weather": "rainy", "temp": "-2.0C"}
print(weather.get("weather")) # rainy
print(weather.get("humidity")) # None
print(weather.get("humidity", "unknown")) # unknown

Dictionary Views

Dictionaries provide three view objects that reflect the current state of the dictionary:

  • .keys(): Returns a view of all keys in the dictionary
  • .values(): Returns a view of all values in the dictionary
  • .items(): Returns a view of all key-value pairs as tuples
weather = {"weather": "rainy", "temp": "-2.0C"}
print(weather.keys()) # dict_keys(['weather', 'temp'])
print(weather.values()) # dict_values(['rainy', '-2.0C'])
print(weather.items()) # dict_items([('weather', 'rainy'), ('temp', '-2.0C')])

Tip

These views are “live” which means they automatically reflect changes to the dictionary. They can be converted to lists if needed: list(dict.keys()).

Checking Membership

Keys can be checked for existence in a dictionary using the in and not in operators:

weather = {"weather": "rainy", "temp": "-2.0C"}
print("weather" in weather) # True
print("humidity" in weather) # False
print("temp" not in weather) # False
# Can also check using .keys()
print("weather" in weather.keys()) # True

Note

The in operator checks for keys, not values. To check if a value exists, use value in dict.values().

Looping Over a Dictionary

A dictionary can be looped over in several ways:

Accessing Keys

Keys can be iterated over directly or using .keys():

weather = {"weather": "rainy", "temp": "-2.0C"}
# Iterate over keys directly
for key in weather:
print(f"{key}={weather[key]}")
# Iterate using .keys()
for key in weather.keys():
print(f"{key}={weather[key]}")

Accessing Values

Values can be iterated over using .values():

weather = {"weather": "rainy", "temp": "-2.0C"}
for value in weather.values():
print(value)

Accessing Key-Value Pairs

The most Pythonic way is to iterate over .items() to get both keys and values:

weather = {"weather": "rainy", "temp": "-2.0C"}
for key, value in weather.items():
print(f"{key}={value}")

Adding and Updating Elements

Single Update

Values can be added or modified by assigning to a key using square brackets. If the key doesn’t exist, it will be added; if it exists, its value will be updated:

weather = {"weather": "rainy"}
weather["temp"] = "-2.0C" # Adds new key-value pair
weather["weather"] = "sunny" # Updates existing key
print(weather) # {'weather': 'sunny', 'temp': '-2.0C'}

Bulk Update with .update()

The .update([E,]**F) method allows merging dictionaries or updating from iterables:

  • If E has a .keys() method (like a dictionary), it does: for k in E: D[k] = E[k]
  • If E lacks .keys() method (like a list of pairs), it does: for k, v in E: D[k] = v
  • Then it processes keyword arguments: for k in F: D[k] = F[k]
d = {}
# Update with dictionary and keyword arguments
d.update({"a": "b"}, c="d", e="f")
print(d) # {'a': 'b', 'c': 'd', 'e': 'f'}
# Update with keyword arguments
d.update(g="h")
print(d) # {'a': 'b', 'c': 'd', 'e': 'f', 'g': 'h'}
# Update with dictionary
d.update({"i": "j"})
print(d) # {'a': 'b', 'c': 'd', 'e': 'f', 'g': 'h', 'i': 'j'}
# Update with list of pairs
d.update([("k", "l")])
print(d) # {'a': 'b', 'c': 'd', 'e': 'f', 'g': 'h', 'i': 'j', 'k': 'l'}
# Update with tuple of pairs
d.update((("m", "n"),))
print(d) # {'a': 'b', 'c': 'd', 'e': 'f', 'g': 'h', 'i': 'j', 'k': 'l', 'm': 'n'}

Removing Elements

There are several ways to remove elements from a dictionary:

Using .pop()

The .pop(key[, default]) method removes the item associated with the key and returns its value. If the key is not present, it returns the default value (if specified) or raises a KeyError:

weather = {"weather": "rainy", "temp": "-2.0C"}
value = weather.pop("weather")
print(value) # rainy
print(weather) # {'temp': '-2.0C'}
# With default value
value = weather.pop("humidity", "unknown")
print(value) # unknown (key didn't exist, returned default)
# Without default (raises KeyError if key doesn't exist)
value = weather.pop("humidity") # KeyError: 'humidity'

Using .clear()

The .clear() method removes all elements from the dictionary:

weather = {"weather": "rainy", "temp": "-2.0C"}
weather.clear()
print(weather) # {}

Using del Statement

The del statement can remove a specific key-value pair:

weather = {"weather": "rainy", "temp": "-2.0C"}
del weather["weather"]
print(weather) # {'temp': '-2.0C'}

Notable Dictionary Methods

.copy()

Creates a shallow copy of the dictionary:

original = {"a": 1, "b": 2}
copy = original.copy()
copy["a"] = 10
print(original) # {'a': 1, 'b': 2}
print(copy) # {'a': 10, 'b': 2}

.fromkeys(iterable, value=None)

Creates a new dictionary with keys from the iterable and all values set to the specified value:

keys = ["a", "b", "c"]
d = dict.fromkeys(keys, 0)
print(d) # {'a': 0, 'b': 0, 'c': 0}
# Without value (defaults to None)
d = dict.fromkeys(keys)
print(d) # {'a': None, 'b': None, 'c': None}

.setdefault(key, default=None)

Inserts the key with the default value if the key is not in the dictionary, then returns the value associated with the key:

weather = {"weather": "rainy"}
# Key exists, returns existing value
value = weather.setdefault("weather", "sunny")
print(value) # rainy
print(weather) # {'weather': 'rainy'}
# Key doesn't exist, adds it and returns default
value = weather.setdefault("temp", "-2.0C")
print(value) # -2.0C
print(weather) # {'weather': 'rainy', 'temp': '-2.0C'}

Built-in Functions with Dictionaries

Several built-in functions can be used with dictionaries:

  • len(dict): Returns the number of key-value pairs
  • all(dict): Returns True if all keys are truthy
  • any(dict): Returns True if any key is truthy
  • sum(dict): Returns the sum of all keys (if they are numeric)
d = {1: "a", 2: "b", 3: "c"}
print(len(d)) # 3
print(all(d)) # True (all keys are truthy)
print(any(d)) # True (at least one key is truthy)
print(sum(d)) # 6 (sum of keys: 1 + 2 + 3)

Why Must Dictionary Keys Be Immutable?

Dictionary keys must be immutable and hashable for several important reasons:

  1. Hash Function: Dictionaries use a hash function to quickly locate values. The hash function generates a unique hash code for each key based on its value. If a key could change after being used, its hash would change, and the dictionary wouldn’t be able to find the value associated with that key.

  2. Consistency: If a key could change, it would create ambiguity. For example, if a key initially maps to value A, then the key changes—should it still map to value A, or should it map to something else? The dictionary wouldn’t know how to handle this.

Exercises

Exercise 1: Create a dictionary with squared values

Create a dictionary such that the keys are from 1 to 10 and for each key x, the value is x**2. Print the dictionary.

Squared Dictionary

Checks: 0 times
Answer:
d = {}
for x in range(1, 11):
d[x] = x ** 2
print(d)

Exercise 2: Merge two dictionaries

Write a program that reads the number of key-value pairs for the first dictionary, then reads each key-value pair, then reads the number of key-value pairs for the second dictionary, then reads each key-value pair, and creates a new dictionary that is the concatenation (merge) of both dictionaries. If there are duplicate keys, the values from the second dictionary should overwrite those from the first. Print the merged dictionary.

Merge Dictionaries

Checks: 0 times
Answer:
n1 = int(input())
dict1 = {}
for i in range(n1):
key = input()
value = input()
dict1[key] = value
n2 = int(input())
dict2 = {}
for i in range(n2):
key = input()
value = input()
dict2[key] = value
merged = dict1.copy()
merged.update(dict2)
print(merged)

Exercise 3: Convert dictionary values to joined strings

Given a dictionary where values are lists of strings, write a program that converts the dictionary into a list of strings where each string is the values from each key joined together. For example, given {"a": ["A", "B"], "b": ["C", "D"]}, the output should be ["AB", "CD"].

Join Dictionary Values

Checks: 0 times
Answer:
D = {"a": ["A", "B"], "b": ["C", "D"]}
result = []
for key in D:
joined = "".join(D[key])
result.append(joined)
print(result)

Exercise 4: What is the output of the following code

What is the output of the following code:

D = {1: 1, 2: '2', '1': 1, '2': 3}
D['1'] = 2
print(D[D[D[str(D[1])]]])
Answer:

The output is: 3

Let’s trace through step by step:

  1. D = {1: 1, 2: '2', '1': 1, '2': 3} - Creates a dictionary with mixed key types (integer and string keys)

  2. D['1'] = 2 - Updates the value for key '1' from 1 to 2, so D = {1: 1, 2: '2', '1': 2, '2': 3}

  3. Now evaluating D[D[D[str(D[1])]]]:

    • D[1] = 1 (gets value for integer key 1)
    • str(D[1]) = str(1) = '1' (converts to string)
    • D[str(D[1])] = D['1'] = 2 (gets value for string key '1')
    • D[D[str(D[1])]] = D[2] = '2' (gets value for integer key 2, which is the string '2')
    • D[D[D[str(D[1])]]] = D['2'] = 3 (gets value for string key '2')

So the final output is 3.

Exercise 5: What is the output of the following code

What is the output of the following code:

D = dict()
for i in range(3):
for j in range(2):
D[i] = j
print(D)
Answer:

The output is: {0: 1, 1: 1, 2: 1}

Let’s trace through the nested loops:

  • i = 0:
    • j = 0: D[0] = 0
    • j = 1: D[0] = 1 (overwrites previous value)
  • i = 1:
    • j = 0: D[1] = 0
    • j = 1: D[1] = 1 (overwrites previous value)
  • i = 2:
    • j = 0: D[2] = 0
    • j = 1: D[2] = 1 (overwrites previous value)

So the final dictionary is {0: 1, 1: 1, 2: 1}.

Exercise 6: Count frequency of characters

Write a program that reads a string and counts the frequency of each character using a dictionary. Print each character and its count on a separate line in the order they first appear.

Character Frequency

Checks: 0 times
Answer:
text = input()
freq = {}
for char in text:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
for char in text:
if freq[char] > 0:
print(f"{char} {freq[char]}")
freq[char] = 0

Exercise 7: Invert a dictionary

Write a program that reads a dictionary size, then reads key-value pairs, and creates a new dictionary where keys and values are swapped. If there are duplicate values in the original dictionary, the last key should be used.

Invert Dictionary

Checks: 0 times
Answer:
n = int(input())
d = {}
for i in range(n):
key = input()
value = input()
d[key] = value
inverted = {}
for key, value in d.items():
inverted[value] = key
print(inverted)

Exercise 8: Find keys with maximum value

Write a program that reads a dictionary size, then reads key-value pairs (where values are integers), and finds all keys that have the maximum value. Print the keys on separate lines.

Keys with Max Value

Checks: 0 times
Answer:
n = int(input())
d = {}
for i in range(n):
key = input()
value = int(input())
d[key] = value
max_value = max(d.values())
for key, value in d.items():
if value == max_value:
print(key)

Exercise 9: Dictionary from two lists

Write a program that reads the size n, then reads n keys, then reads n values, and creates a dictionary from these two lists where the i-th key is paired with the i-th value.

Dictionary from Lists

Checks: 0 times
Answer:
n = int(input())
keys = []
for i in range(n):
keys.append(input())
values = []
for i in range(n):
values.append(input())
d = {}
for i in range(n):
d[keys[i]] = values[i]
print(d)

Exercise 10: Remove all keys with even values

Write a program that reads a dictionary size, then reads key-value pairs (where values are integers), and removes all keys whose values are even numbers. Print the modified dictionary.

Remove Even Values

Checks: 0 times
Answer:
n = int(input())
d = {}
for i in range(n):
key = input()
value = int(input())
d[key] = value
keys_to_remove = []
for key, value in d.items():
if value % 2 == 0:
keys_to_remove.append(key)
for key in keys_to_remove:
del d[key]
print(d)

Course Progress

Section 25 of 61

Back to Course