• Home
  • LLMs
  • Python
  • Docker
  • Kubernetes
  • Java
  • Maven
  • All
  • About
Python | Dictionaries
A dictionary is a mutable collection of ordered key-value pairs.
Keys must be unique (no duplicate keys) and immutable (strings, numbers, tuples) The values can be of any type, including mixed types within the same dictionary: strings, numbers, dictionaries, lists, objects, ...

Creating basic dictionaries:
Use braces ({}) to create a dictionary.
Use commas to separate items in the dictionary.

Empty dictionary:
x = {}
y = dict()
print(type(x)) # Output: <class 'dict'>
print(x) # Output: {}
A dictionary with one key-value pair:
print({'a': 1}) # Output: {'a': 1}
A dictionary with multiple key-value pairs:
print({'a': 1, 'b': 2}) # Output: {'a': 1, 'b': 2}
Mixed data types:
x = {'a': 1, 'b': 'B', 'c': [1, 2], 'd': (1, 2), 'e': {1, 2}, 'f': {'w': 10}}
print(x) # Output: {'a': 1, 'b': 'B', 'c': [1, 2], 'd': (1, 2), 'e': {1, 2}, 'f': {'w': 10}}
List/Set/Dictionary of dictionaries:
x = {'a': 1, 'b': 2}
y = {'c': 2, 'd': 3}

# list of dictionaries
z = [x, y]

# dictionary of list, set, and dictionaries
d = {'r': x, 's': y, 't': z}

# dictionaries cannot be elements of sets because they're mutable and therefore unhashable
#w = {x, y} # Raises TypeError: unhashable type: 'dict'

print(z) # Output: [{'a': 1, 'b': 2}, {'c': 2, 'd': 3}]
print(z[0]['b']) # Output: 2

print(d) # Output: {'r': {'a': 1, 'b': 2}, 's': {'c': 2, 'd': 3}, 't': [{'a': 1, 'b': 2}, {'c': 2, 'd': 3}]}
print(d['t'][0]['b']) # Output: 2
Create dictionaries using dict() with keyword arguments:
print(dict(a='A', b='B')) # Output: {'a': 'A', 'b': 'B'}
Create dictionaries using dict() with list of tuples:
print(dict([('a', 'A'), ('b', 'B')])) # Output: {'a': 'A', 'b': 'B'}
Create dictionaries using dictionary comprehension:
print({x: x**2 for x in range(3)}) # Output: {0: 0, 1: 1, 2: 4}
Tuples as dictionary keys:
This is possible because tuples are immutable.
numbers = {(0, 0):0, (0, 1):1, (1, 0):2, (1, 1):3}
print(numbers[(0,1)]) # Output: 1
print(numbers.get((0,1))) # Output: 1
print(numbers.get((0,2))) # Output: None
print(numbers.get((0,2), "undetermined")) # Output: undetermined
Accessing keys in a dictionary:
x = {'a': 1, 'b': 2}
print(x['a']) # Output: 1
Accessing a key that doesn't exist throws an error:
print(x['d']) # Raises KeyError: 'd'

# to handle the KeyError: use try/except
try:
  print(x['d'])
except KeyError as e:
  print(f"key not found: {e}") # Output: key not found: 'd'

# to handle the KeyError: check if key exists
if 'd' in x:
  print(x['d'])
else:
  print("key 'd' not found")
Using the get function:
It returns default/custom value if the key doesn't exist.
print(x.get('a')) # Output: 1

# return None if key doesn't exist
print(x.get('d')) # Output: None

# return custom value if key doesn't exist
print(x.get('d','key not found')) # Output: key not found
Adding new key-value pairs:
x['c'] = 3
print(x) # Output: {'a': 1, 'b': 2, 'c': 3}

# use setdefault() to add a key-value pair only if the key doesn't exist
x.setdefault('c', 33)
x.setdefault('d', 4)
print(x) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Modifying values in a dictionary:
x['a'] = 0
print(x['a']) # Output: 0
Using update() method:
# update using dictionaries
x.update({'a': 'A', 'b': 'B'})
print(x) # Output: {'a': 'A', 'b': 'B', 'c': 3, 'd': 4}

# update using keyword arguments
x.update(c='C', d='D')
print(x) # Output: {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}
Removing key-value pairs:
# using del statement
del x['d']
print(x) # Output: {'a': 'A', 'b': 'B', 'c': 'C'}

# you get a KeyError if the key doesn't exist; need to handle the exception or check if the key exists
del x['d'] # Raises KeyError: 'd'
Removing a specific key and returning its value:
# using pop() method to remove a specific key
print(x.pop('c')) # Output: 'C'
print(x) # Output: {'a': 'A', 'b': 'B'}

# you get a KeyError if the key doesn't exist; need to handle the exception or check if the key exists
print(x.pop('c')) # Raises KeyError: 'c'
Removing a specific key and returning a tuple with key/value:
# using popitem() method to remove last item
print(x.popitem()) # Output: ('b', 'B')
print(x) # Output: {'a': 'A'}

# you get a KeyError if the dictionary is empty: need to handle the exception or check the length of the dictionary
print(x.popitem()) # Output: ('a', 'A')
print(x) # Output: {}
print(x.popitem()) # Raises KeyError: 'popitem(): dictionary is empty'
Clear dictionary (remove all items):
x = {'a': 1, 'b': 2, 'c': 3}
x.clear()
print(x) # Output: {}
Looping through all key-value pairs:
x = {'a': 1, 'b': 2, 'c': 3}
for key, value in x.items():
  print(f'key:{key} | value:{value}')
Output:
key:a | value:1
key:b | value:2
key:c | value:3
Looping through all keys in a dictionary:
# default behavior
for key in x:
  print(f'key:{key} | value:{x[key]}')

print()

# explicitly iterate over keys
for key in x.keys(): # calling the keys() function is similar to looping on the dictionary itself
  print(f'key:{key} | value:{x[key]}')
Output:
key:a | value:1
key:b | value:2
key:c | value:3

key:a | value:1
key:b | value:2
key:c | value:3
Looping through all values in a dictionary:
for value in x.values():
  print(f'value:{value}')
Output:
value:1
value:2
value:3
Looping through all sorted keys:
for key in sorted(x.keys()):
  print(f'key:{key} | value:{x[key]}')
Output:
key:a | value:1
key:b | value:2
key:c | value:3
Looping through all sorted keys (reversed order):
for key in sorted(x.keys(), reverse=True):
  print(f'key:{key} | value:{x[key]}')
Output:
key:c | value:3
key:b | value:2
key:a | value:1
Looping through all sorted values (reversed order):
for key in sorted(x, key=x.get):
  print(f'key:{key} | value:{x[key]}')
Output:
key:a | value:1
key:b | value:2
key:c | value:3
Looping through all the unique values in a dictionary:
x = {'a': 1, 'b': 2, 'c': 2}
for value in set(x.values()):
  print(f'value:{value}')
Output:
value:1
value:2
Dictionary comprehensions:
x = [1, 2, 3]

# create dictionary from list
print({k: k**2 for k in x}) # Output: {1: 1, 2: 4, 3: 9}

# create dictionary from list with condition
print({k: k**2 for k in x if k % 2 == 1}) # Output: {1: 1, 3: 9}

# create dictionary from two lists
y = ['a', 'b', 'c']
print({k: v for k, v in zip(x, y)}) # Output: {1: 'a', 2: 'b', 3: 'c'}
Merging Dictionaries:
Conflicting keys will be resolved by taking the values from the last dictionary in the list of dictionaries to merge:
x = {'a': 'A', 'b': 'B'}
y = {'b': 'b', 'd': 'D'}

# using ** operator: new dictionary created
print({**x, **y}) # Output: {'a': 'A', 'b': 'b', 'd': 'D'}

# using | operator: new dictionary created
print(x | y) # Output: {'a': 'A', 'b': 'b', 'd': 'D'}

# using update method: original dictionary updated
x.update(y)
print(x) # Output: {'a': 'A', 'b': 'b', 'd': 'D'}
Copying dictionaries:
x = {'r': {'a': 1, 'b': 2}, 's': {'c': 2, 'd': 3}, 't': [{'a': 1, 'b': 2}, {'c': 2, 'd': 3}]}

# copy by reference
y = x # both x and y reference the same dictionary
y['r'] = 0
print(x['r']) # Output: 0

# copy by value
z = x.copy() # new copy
w = dict(x) # new copy
z['s'] = 3
print(x['s']) # Output: {'c': 2, 'd': 3}
print(z['s']) # Output: 3
print(w['s']) # Output: {'c': 2, 'd': 3}
© 2025  mtitek