Dictionary in Python is a collection of key/value pairs. Dictionaries use keys(labels) to store item/value references, instead of numbered index.
Python Dictionary is a unordered and mutable collection of Zero(0) or more key/value pairs.
Only hashable objects can be used as key in a Dictionary.
Dictionary items are not ordered, and are not stored in any specific order.
Define a Dictionary
There are several ways we can define a dictionary-
Method #1: Dictionary Literal
We can use “dict()” to create a new dictionary. Check the example below-
product_info = dict({
"name": "Sonic Wireless Headphones",
"model": "SWH-30G21",
"category": "Electronics > Audio > Headphones",
"color": "Black",
"weight": "0.5lbs",
"battery_life": "30h",
"speaker_size": "40mm",
"price": "99.99",
})
print(product_info)
print(type(product_info))
print(len(product_info))
product_info['sku'] = "K66GH4YF4HH"
product_info['description'] = "dummy description of the product"
product_info['model'] = "MMM-30G21"
print(product_info)
print(len(product_info))
print(dir(product_info))
PythonOutput:
{'name': 'Sonic Wireless Headphones', 'model': 'SWH-30G21', 'category': 'Electronics > Audio > Headphones', 'color': 'Black', 'weight': '0.5lbs', 'battery_life': '30h', 'speaker_size': '40mm', 'price': '99.99'}
<class 'dict'>
8
{'name': 'Sonic Wireless Headphones', 'model': 'MMM-30G21', 'category': 'Electronics > Audio > Headphones', 'color': 'Black', 'weight': '0.5lbs', 'battery_life': '30h', 'speaker_size': '40mm', 'price': '99.99', 'sku': 'K66GH4YF4HH', 'description': 'dummy description of the product'}
10
['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
PlaintextMethod #2: Dictionary Literal without dict()
Or we can define and assign key/value as below-
product_info = {
"name": "Sonic Wireless Headphones",
"model": "SWH-30G21",
"category": "Electronics > Audio > Headphones",
"color": "Black",
"weight": "0.5lbs",
"battery_life": "30h",
"speaker_size": "40mm",
"price": "99.99",
}
print(type(product_info))
print(len(product_info))
print(product_info)
print(dir(product_info))
PythonOutput:
<class 'dict'>
8
{'name': 'Sonic Wireless Headphones', 'model': 'SWH-30G21', 'category': 'Electronics > Audio > Headphones', 'color': 'Black', 'weight': '0.5lbs', 'battery_life': '30h', 'speaker_size': '40mm', 'price': '99.99'}
['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
PlaintextMethod #3: Keyword Argument
Use dictionary literal to define a dictionary-
product_info = dict(
id=1,
name="Sonic Wireless Headphones",
model="SWH-30G21",
)
print(product_info)
PythonOutput:
{'id': 1, 'name': 'Sonic Wireless Headphones', 'model': 'SWH-30G21'}
PlaintextMethod #4: List of Tuple
Define key/value in separate tuples and then create a list of those tuples. Pass the list to dict(), and a dictionary will be created from that-
product_info = dict([("id", 1), ("name", "Sonic Wireless Headphones"), ("model", "SWH-30G21")])
print(product_info)
PythonOutput:
{'id': 1, 'name': 'Sonic Wireless Headphones', 'model': 'SWH-30G21'}
PlaintextMethod #3: From zip
We can define our keys and values using zip, and then pass that to dict() function-
product_info = dict(
zip(("id", "name", "model"), (1, "Sonic Wireless Headphones", "SWH-30G21"))
)
print(product_info)
PythonOutput:
{'id': 1, 'name': 'Sonic Wireless Headphones', 'model': 'SWH-30G21'}
PlaintextAccess Dictionary Item
We can access dictionary value by key or by using “get()” function.
product_info = {
"name": "Sonic Wireless Headphones",
"model": "SWH-30G21",
"category": "Electronics > Audio > Headphones",
"color": "Black",
"weight": "0.5lbs",
"battery_life": "30h",
"speaker_size": "40mm",
"price": "99.99",
}
name = product_info['name']
print("name: ", name)
model = product_info.get('model')
print("model: ", model)
PythonOutput:
name: Sonic Wireless Headphones
model: SWH-30G21
PlaintextIf the key does not exist and we try to get it, then it throws a KeyError-
product_info = {
"name": "Sonic Wireless Headphones",
"model": "SWH-30G21",
}
unknown = product_info['unknown_key']
print("unknown: ", unknown)
PythonOutput:
Traceback (most recent call last):
File "dict_ex.py", line 20, in <module>
unknown = product_info['unknown_key']
KeyError: 'unknown_key'
PlaintextTo overcome this, we can use the “get()” function. If the key does not exist, then the “get()” function will return “None”.
We can pass some default value to “get()” to ensure some custom default value, if the key do not exist.
product_info = {
"name": "Sonic Wireless Headphones",
"model": "SWH-30G21",
}
unknown = product_info.get('unknown_key')
print("unknown: ", unknown)
unknown_with_default = product_info.get('unknown_key', 'some default value')
print("unknown with default: ", unknown_with_default)
PythonOutput:
unknown: None
unknown with default: some default value
PlaintextHashable Key
Key of the dictionary key/value pair, can be any hashable. The data types that are hashable(has __hash__ function) can be used as key.
For example, in the following code we are using a tuple, and frozen set as key-
big_box_dict = {
"first key": 100,
frozenset((1, 2, 3, 4)): 200,
('big', 'box', 'code'): "name of the application"
}
print(big_box_dict)
PythonOutput:
{'first key': 100, frozenset({1, 2, 3, 4}): 200, ('big', 'box', 'code'): 'name of the application'}
PlaintextLoop through Dictionary
Let’s see how can we loop though the items of a dictionary.
Case #1: Keys Only
product_info = {
"name": "Sonic Wireless Headphones",
"model": "SWH-30G21",
"category": "Electronics > Audio > Headphones",
"color": "Black",
"weight": "0.5lbs",
"battery_life": "30h",
"speaker_size": "40mm",
"price": "99.99",
}
for info_key in product_info:
print(info_key)
PythonOutput:
name
model
category
color
weight
battery_life
speaker_size
price
PlaintextWe can fine the value, by using the key-
product_info = {
"name": "Sonic Wireless Headphones",
"model": "SWH-30G21",
"category": "Electronics > Audio > Headphones",
"color": "Black",
"weight": "0.5lbs",
"battery_life": "30h",
"speaker_size": "40mm",
"price": "99.99",
}
for info_key in product_info:
print(f"Key: {info_key} || Value: {product_info[info_key]}")
PythonOutput:
Key: name || Value: Sonic Wireless Headphones
Key: model || Value: SWH-30G21
Key: category || Value: Electronics > Audio > Headphones
Key: color || Value: Black
Key: weight || Value: 0.5lbs
Key: battery_life || Value: 30h
Key: speaker_size || Value: 40mm
Key: price || Value: 99.99
PlaintextCase #2: Values only
product_info = {
"name": "Sonic Wireless Headphones",
"model": "SWH-30G21",
"category": "Electronics > Audio > Headphones",
"color": "Black",
"weight": "0.5lbs",
"battery_life": "30h",
"speaker_size": "40mm",
"price": "99.99",
}
for info in product_info.values():
print(info)
PythonOutput:
Sonic Wireless Headphones
SWH-30G21
Electronics > Audio > Headphones
Black
0.5lbs
30h
40mm
99.99
PlaintextCase #3: Key and Value both
product_info = {
"name": "Sonic Wireless Headphones",
"model": "SWH-30G21",
"category": "Electronics > Audio > Headphones",
"color": "Black",
"weight": "0.5lbs",
"battery_life": "30h",
"speaker_size": "40mm",
"price": "99.99",
}
for info_key, value in product_info.items():
print(f"Key: {info_key} || Value: {value}")
PythonOutput:
Key: name || Value: Sonic Wireless Headphones
Key: model || Value: SWH-30G21
Key: category || Value: Electronics > Audio > Headphones
Key: color || Value: Black
Key: weight || Value: 0.5lbs
Key: battery_life || Value: 30h
Key: speaker_size || Value: 40mm
Key: price || Value: 99.99
Plaintextcollections.defaultdict()
Python collections module has an implementation of a dictionary named “defaultdict“. “defaultdict” has the following specialty over normal dictionary-
- Does not throw KeyError, if the key does not exist.
- Keys have default value(if a type is provided). So it will not throw KeyError if key does not exist.
Define a “defaultdict” from “collections” module.
import collections
big_box_defaultdict = collections.defaultdict()
print(big_box_defaultdict)
PythonOutput:
defaultdict(None, {})
PlaintextPass a specific data type to the “defaultdict” function to ensure a specific type of element in the dictionary-
import collections
big_box_defaultdict = collections.defaultdict(int)
print(big_box_defaultdict)
PythonOutput:
defaultdict(<class 'int'>, {})
PlaintextIf we access a non existing key, then defaultdict will return the default value of the data type, that we provided while initializeing the “defaultdict”-
import collections
big_box_defaultdict = collections.defaultdict(int)
print(big_box_defaultdict)
unknown = big_box_defaultdict['unknown_key']
print("unknown: ", unknown)
PythonOutput:
defaultdict(<class 'int'>, {})
unknown: 0
Plaintext WARNING
If the type is not provided to “defaultdict” then it will still throw KeyError, if we try to access a unknown key. As the default value can not be determined without the type.
import collections
big_box_defaultdict = collections.defaultdict()
unknown = big_box_defaultdict['unknown_key']
print("unknown: ", unknown)
PythonOutput:
Traceback (most recent call last):
File "default_dict.py", line 7, in <module>
unknown = big_box_defaultdict['unknown_key']
KeyError: 'unknown_key'
PlaintextAny type of value can be saved in a “defaultdict”. The type is just for the default value-
import collections
big_box_defaultdict = collections.defaultdict(int)
big_box_defaultdict['first_key'] = 100
big_box_defaultdict['second_key'] = 99.99
big_box_defaultdict['third_key'] = "bigboxcode"
print(big_box_defaultdict)
PythonOutput:
defaultdict(<class 'int'>, {'first_key': 100, 'second_key': 99.99, 'third_key': 'bigboxcode'})
Plaintextcollections.OrderedDict()
Default dictionary in Python does not hold the item order. But OrderedDict is a dictionary implementation that-
- Stores the order, in which it was inserted.
- If some value is changed, then the order(previous/old) of the item is maintained.
import collections
product_info = collections.OrderedDict([("id", 1), ("name", "Sonic Wireless Headphones"), ("model", "SWH-30G21")])
product_info['color'] = "Black"
product_info["weight"] = "0.5lbs"
print(product_info)
PythonOutput:
OrderedDict([('id', 1), ('name', 'Sonic Wireless Headphones'), ('model', 'SWH-30G21'), ('color', 'Black'), ('weight', '0.5lbs')])
Plaintext NOTES
If we want to change the order of items. Then we have to delete items(as per our requirement) and then reinsert the items.