Python dictionary is an unordered collection of items. While other compound datatypes have only value as an element, a dictionary has a key: value pair. Dictionaries are optimized to retrieve values when the key is known.
Python Dictionary Creating
Creating a dictionary is as simple as placing items inside curly braces { } separated by comma. An item has a key and the corresponding value expressed as a pair, key: value. While values can be of any datatype and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique. We can also create a dictionary using the built-in function dict().
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'Monday', 2: 'Tuesday'}
# dictionary with mixed keys
my_dict = {'name': 'matmock', 1: [12, 4, 33]}
# using dict()
my_dict = dict({1:'Monday', 2:'Tuesday'})
# from sequence having each item as a pair
my_dict = dict([(1,'Monday'), (2,'Tuesday')])
Python Dictionary Accessing Elements
While indexing is used with other container types to access values, dictionary uses keys. Key can be used either inside square brackets or with the get() method. The differencewhile using get() is that it returns None instead of KeyError, if the key is not found.
>>> my_dict = {'name':'matmock', 'age': 2}
>>> my_dict['name']
'matmock'
>>> my_dict.get('age')
2
>>> my_dict.get('address')
>>> my_dict['address']
...
KeyError: 'address'
Python Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create new dictionary from an iterable in Python. Dictionary comprehension consists of an expression pair (key: value) followed by for statement inside curly braces {}. Here is an example to make a dictionary with each item being a pair of a number and its square.
>>> squares = {x: x*x for x in range(6)}
>>> squares
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
This code is equivalent to
squares = {}
for x in range(6):
squares[x] = x*x
A dictionary comprehension can optionally contain more for or if statements. An optional if statement can filter out items to form the new dictionary. Here are some examples to make dictionary with only odd items.
>>> odd_squares = {x: x*x for x in range(11) if x%2 == 1}
>>> odd_squares
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
Python Dictionary Append
Dictionary are mutable. We can add new items or change the value of existing items using assignment operator. If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.
>>> my_dict
{'age': 2, 'name': 'matmock'}
>>> my_dict['age'] = 2.5 # update value
>>> my_dict
{'age': 2.5, 'name': 'matmock'}
>>> my_dict['address'] = 'matmock.in' # add item
>>> my_dict
{'address': 'matmock.in', 'age': 2.5, 'name': 'matmock'}
Python Dictionary Remove or Delete Element
We can remove a particular item in a dictionary by using the method pop(). This method removes as item with the provided key and returns the value. The method, popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary. All the items can be removed at once using the clear() method. We can also use the del keyword to remove individual items or the entire dictionary itself.
>>> squares = {1:1, 2:4, 3:9, 4:16, 5:25} # create a dictionary
>>> squares.pop(4) # remove a particular item
16
>>> squares
{1: 1, 2: 4, 3: 9, 5: 25}
>>> squares.popitem() # remove an arbitrary item
(1, 1)
>>> squares
{2: 4, 3: 9, 5: 25}
>>> del squares[5] # delete a particular item
>>> squares
{2: 4, 3: 9}
>>> squares.clear() # remove all items
>>> squares
{}
>>> del squares # delete the dictionary itself
>>> squares
...
NameError: name 'squares' is not defined
Python Dictionary Functions
Python includes following dictionary functions
Sr.No | Python Dictionary Function with Description |
---|---|
1 | cmp(dict1, dict2) Compares elements of both dict. |
2 | len(dict) Gives the total length of the dictionary. This would be equal to the number of items in the dictionary. |
3 | str(dict) Produces a printable string representation of a dictionary |
4 | type(variable) Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.
|
Python Dictionary Methods
Python includes following dictionary methods
Sr.No | Python Dictionary Methods with Description |
---|---|
1 | dict.clear() Removes all elements of dictionary dict
|
2 | dict.copy() Returns a shallow copy of dictionary dict |
3 | dict.fromkeys() Create a new dictionary with keys from seq and values set to value. |
4 | dict.get(key, default=None) For key key, returns value or default if key not in dictionary |
5 | dict.has_key(key) Returns true if key in dictionary dict, false otherwise |
6 | dict.items() Returns a list of dict's (key, value) tuple pairs |
7 | dict.keys() Returns list of dictionary dict's keys |
8 | dict.setdefault(key, default=None) Similar to get(), but will set dict[key]=default if key is not already in dict |
9 | dict.update(dict2) Adds dictionary dict2's key-values pairs to dict |
10 | dict.values() Returns list of dictionary dict's values |