Collections of key-value pairs.

In [1]:
my_empty_dict = {}  # alternative: my_empty_dict = dict()
print('dict: {}, type: {}'.format(my_empty_dict, type(my_empty_dict)))
dict: {}, type: <class 'dict'>


In [2]:
dict1 = {'value1': 1.6, 'value2': 10, 'name': 'John Doe'}
dict2 = dict(value1=1.6, value2=10, name='John Doe')


print('equal: {}'.format(dict1 == dict2))
print('length: {}'.format(len(dict1)))
{'value1': 1.6, 'name': 'John Doe', 'value2': 10}
{'value2': 10, 'name': 'John Doe', 'value1': 1.6}
equal: True
length: 3

dict.keys(), dict.values(), dict.items()

In [3]:
print('keys: {}'.format(dict1.keys()))
print('values: {}'.format(dict1.values()))
print('items: {}'.format(dict1.items()))
keys: dict_keys(['value1', 'name', 'value2'])
values: dict_values([1.6, 'John Doe', 10])
items: dict_items([('value1', 1.6), ('name', 'John Doe'), ('value2', 10)])

Accessing and setting values

In [4]:
my_dict = {}
my_dict['key1'] = 'value1'
my_dict['key2'] = 99
my_dict['key1'] = 'new value'  # overriding existing value
print('value of key1: {}'.format(my_dict['key1']))
{'key2': 99, 'key1': 'new value'}
value of key1: new value

Accessing a nonexistent key will raise KeyError (see dict.get() for workaround):

In [5]:
# print(my_dict['nope'])


In [6]:
my_dict = {'key1': 'value1', 'key2': 99, 'keyX': 'valueX'}
del my_dict['keyX']

# Usually better to make sure that the key exists (see also pop() and popitem())
key_to_delete = 'my_key'
if key_to_delete in my_dict:
    del my_dict[key_to_delete]
    print('{key} is not in {dictionary}'.format(key=key_to_delete, dictionary=my_dict))
{'key2': 99, 'key1': 'value1'}
my_key is not in {'key2': 99, 'key1': 'value1'}

Dictionaries are mutable

In [7]:
my_dict = {'ham': 'good', 'carrot': 'semi good'}
my_other_dict = my_dict
my_other_dict['carrot'] = 'super tasty'
my_other_dict['sausage'] = 'best ever'
print('my_dict: {}\nother: {}'.format(my_dict, my_other_dict))
print('equal: {}'.format(my_dict == my_other_dict))
my_dict: {'carrot': 'super tasty', 'ham': 'good', 'sausage': 'best ever'}
other: {'carrot': 'super tasty', 'ham': 'good', 'sausage': 'best ever'}
equal: True

Create a new dict if you want to have a copy:

In [8]:
my_dict = {'ham': 'good', 'carrot': 'semi good'}
my_other_dict = dict(my_dict)
my_other_dict['beer'] = 'decent'
print('my_dict: {}\nother: {}'.format(my_dict, my_other_dict))
print('equal: {}'.format(my_dict == my_other_dict))
my_dict: {'carrot': 'semi good', 'ham': 'good'}
other: {'beer': 'decent', 'carrot': 'semi good', 'ham': 'good'}
equal: False


Returns None if key is not in dict. However, you can also specify default return value which will be returned if key is not present in the dict.

In [9]:
my_dict = {'a': 1, 'b': 2, 'c': 3}
d = my_dict.get('d')
print('d: {}'.format(d))

d = my_dict.get('d', 'my default value')
print('d: {}'.format(d))
d: None
d: my default value


In [10]:
my_dict = dict(food='ham', drink='beer', sport='football')
print('dict before pops: {}'.format(my_dict))

food = my_dict.pop('food')
print('food: {}'.format(food))
print('dict after popping food: {}'.format(my_dict))

food_again = my_dict.pop('food', 'default value for food')
print('food again: {}'.format(food_again))
print('dict after popping food again: {}'.format(my_dict))
dict before pops: {'sport': 'football', 'drink': 'beer', 'food': 'ham'}
food: ham
dict after popping food: {'sport': 'football', 'drink': 'beer'}
food again: default value for food
dict after popping food again: {'sport': 'football', 'drink': 'beer'}


Returns the value of key defined as first parameter. If the key is not present in the dict, adds key with default value (second parameter).

In [11]:
my_dict = {'a': 1, 'b': 2, 'c': 3}
a = my_dict.setdefault('a', 'my default value')
d = my_dict.setdefault('d', 'my default value')
print('a: {}\nd: {}\nmy_dict: {}'.format(a, d, my_dict))
a: 1
d: my default value
my_dict: {'a': 1, 'c': 3, 'b': 2, 'd': 'my default value'}


Merge two dicts

In [12]:
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3}

# If they have same keys:
dict1.update({'c': 4})
{'a': 1, 'c': 3, 'b': 2}
{'a': 1, 'c': 4, 'b': 2}

The keys of a dict have to be immutable

Thus you can not use e.g. a list or a dict as key because they are mutable types :

In [13]:
# bad_dict = {['my_list'], 'value'}  # Raises TypeError

Values can be mutable

In [14]:
good_dict = {'my key': ['Python', 'is', 'still', 'cool']}
{'my key': ['Python', 'is', 'still', 'cool']}