In this tutorial, we’re gonna look at Python Dictionary data type: what it is, how to create, add, access, remove item and Python built-in methods.
Related Post: Python List functions
Python Dictionary data type
Python Dictionary is a collection of items. Unlike List, Dictionary doesn’t have indexes but keys. A key with its associated value is called a key-value pair.
Dictionary is covered by braces ({}
):
>>> customer = {'name': 'Jack', 'age': 42, 'location': 'US'} # keys: 'name', 'age', 'location' # values: 'Jack', 42, 'US' >>> customer['name'] 'Jack' >>> customer['age'] 42 >>> customer['location'] 'US'
Create a Python Dictionary
Usual way
We can use integer values as keys, just like List for indexes, but they do not have to start at 0
and can be any number:
>>> mPair = {123: 'One Two Three', 42: 'The Answer', 1: [1, 2, 3]} >>> mPair[123] 'One Two Three' >>> mPair[42] 'The Answer' >>> mPair[1] [1, 2, 3]
Dictionary can be created with mixed keys:
# keys must be immutable types (string, number or tuple with immutable elements) >>> mDic = {'first': 1, 42: 'The Answer', ('Jack', 25): 'My Friend'} >>> mDic['first'] 1 >>> mDic[42] 'The Answer' >>> mDic[('Jack',25)] 'My Friend'
Use dict() contructor
We can also create a Dictionary with dict()
built-in function:
>>> mList = [('first', 1), (42, 'The Answer')] >>> mDict = dict(mList) >>> mDict {42: 'The Answer', 'first': 1}
If the keys are simple strings:
>>> dict(jack=12, adam=3, katherin=26) {'katherin': 26, 'adam': 3, 'jack': 12}
Use Python Dictionary Comprehension
>>> {'key_'+ str(i): i**2 for i in (1, 2, 3, 4, 5)} {'key_1': 1, 'key_4': 16, 'key_3': 9, 'key_2': 4, 'key_5': 25}
Access items from Python Dictionary
Usual way
Use key inside square brackets:
>>> customer = {'name': 'Jack', 'age': 42, 'location': 'US'} # keys: 'name', 'age', 'location' >>> customer['name'] 'Jack' >>> customer['age'] 42 >>> customer['location'] 'US' >>> customer['company'] Traceback (most recent call last): File "", line 1, in KeyError: 'company'
Use get() method
We can use get()
method that returns None
instead of KeyError
when the key is not found:
>>> customer = {'name': 'Jack', 'age': 42, 'location': 'US'} # keys: 'name', 'age', 'location' >>> customer.get('name') 'Jack' >>> customer.get('age') 42 >>> customer.get('location') 'US' >>> customer.get('company') >>>
Access all keys/values – Iterate a Python Dictionary
>>> customer = {'name': 'Jack', 'age': 42, 'location': 'US'} # access all keys with keys() method >>> customer.keys() dict_keys(['name', 'location', 'age']) >>> for key in customer.keys(): ... print(key) ... name location age # access all values with values() method >>> customer.values() dict_values(['Jack', 'US', 42]) >>> for value in customer.values(): ... print(value) ... Jack US 42 # access all key-value pairs with items() method >>> customer = {'name': 'Jack', 'age': 42, 'location': 'US'} >>> customer.items() dict_items([('name', 'Jack'), ('location', 'US'), ('age', 42)]) >>> for key, value in customer.items(): ... print('{}: {}'.format(key, value)) ... name: Jack location: US age: 42
Add item to Python Dictionary
– The simplest way is using a new key and assign a value:
>>> customer = {'name': 'Jack', 'age': 42, 'location': 'US'} >>> customer['company'] = 'ozenero' >>> customer {'name': 'Jack', 'location': 'US', 'age': 42, 'company': 'ozenero'}
– Or we can use update()
method:
>>> customer = {'name': 'Jack', 'age': 42, 'location': 'US'} >>> customer.update({'company': 'ozenero'}) >>> customer {'name': 'Jack', 'location': 'US', 'age': 42, 'company': 'ozenero'}
Update an item of Python Dictionary
Similar to add an item, but instead of using a new key, we update with the old key:
>>> customer = {'name': 'Jack', 'location': 'US', 'age': 42, 'company': 'ozenero'} >>> customer['company'] = 'ozenero Technology' >>> customer {'name': 'Jack', 'location': 'US', 'age': 42, 'company': 'ozenero Technology'} # use update() method >>> customer = {'name': 'Jack', 'location': 'US', 'age': 42, 'company': 'ozenero'} >>> customer.update({'company': 'ozenero Technology'}) >>> customer {'name': 'Jack', 'location': 'US', 'age': 42, 'company': 'ozenero Technology'}
Remove an item from Python Dictionary
Pop item by key
pop()
method to remove item by its key:
>>> customer = {'name': 'Jack', 'location': 'US', 'age': 42, 'company': 'ozenero'} >>> customer.pop('company') 'ozenero' >>> customer {'name': 'Jack', 'location': 'US', 'age': 42}
Pop arbitrary item
popitem()
method to remove arbitrary item:
>>> customer = {'name': 'Jack', 'location': 'US', 'age': 42, 'company': 'ozenero'} >>> customer.popitem() ('name', 'Jack') >>> customer {'location': 'US', 'age': 42, 'company': 'ozenero'}
*Note: From version 3.7: LIFO order. In prior versions, popitem()
for arbitrary item.
Remove all items
We can keep the dictionary and remove all items with clear()
method:
>>> customer = {'name': 'Jack', 'location': 'US', 'age': 42, 'company': 'ozenero'} >>> customer = {'name': 'Jack', 'age': 42, 'location': 'US'} >>> customer.clear() >>> customer {}
Use del statement
– del
statement to remove specific item (by key):
>>> customer = {'name': 'Jack', 'location': 'US', 'age': 42, 'company': 'ozenero'} >>> del customer['company'] >>> customer {'name': 'Jack', 'location': 'US', 'age': 42}
– delete the dictionary completely (this is different from clear()
method):
>>> customer = {'name': 'Jack', 'location': 'US', 'age': 42} >>> del customer >>> customer Traceback (most recent call last): File "", line 1, in NameError: name 'customer' is not defined
Check if a key/value exists in Python Dictionary
We can know whether a key/value is or is not in Dictionary using in
and not in
operators:
>>> customer = {'name': 'Jack', 'age': 42, 'location': 'US'} >>> 'age' in customer.keys() True >>> 'Jack' in customer.values() True >>> 'ozenero' in customer.values() False >>> 'ozenero' not in customer.values() True >>> 'location' not in customer.keys() False # 'in customer' is short version of 'in customer.keys()' >>> 'location' in customer True
Set default value for a key in Python Dictionary
Sometimes we want to set default value for a key that doesn’t already have a value. It’s something like this:
>>> customer = {'name': 'Jack', 'age': 42} >>> if 'location' not in customer: ... customer['location'] = 'US'
setdefault()
method can make this happen in just one line of code:
>>> customer = {'name': 'Jack', 'age': 42} >>> customer.setdefault('location','US') 'US' >>> customer {'age': 42, 'location': 'US', 'name': 'Jack'} >>> customer.setdefault('location','Canada') 'US' >>> customer {'age': 42, 'location': 'US', 'name': 'Jack'}
Python Dictionary built-in functions
– all()
: returns True
if all keys are true, or if dictionary is empty.
– any()
: returns True
if any key is true, returns False
if dictionary is empty.
– len()
: returns number of items in dictionary.
– sorted()
: returns a new sorted list of keys in the dictionary.
>>> customer = {'name': 'Jack', 'age': 42, 'location': 'US'} >>> len(customer) 3 >>> sorted(customer) ['age', 'location', 'name']