About Python Dictionaries

tags: #python/documentation/dictionaries

What are Python Dictionaries?

A dictionary is a another type of built-in data structure in Python using to store data values in key:value pairs (referred to as an "item").

What is a key:value pair?

The key-value pair concept allows you to retrieve values based on their corresponding keys. The key is mapped to an associated value.

⚠ Switch to EXCALIDRAW VIEW in the MORE OPTIONS menu of this document. ⚠

Text Elements

Keys
Values
'a'
'b'
'c'
'apple'
'banana'
'carrot'
To retrieve the values, we call the corresponding key that is associated to the value

Dictionary Key Constraints

Keys are immutable but the key-value pair itself is

While the keys in a dictionary cannot be modified, the entirety of the key:value pair can be added or removed from a dictionary.


Creating a Dictionary

We can create an instance of a dictionary using curly braces {} with one or more key:value pairs (note: a : is used to separate the key from its associated value)

a_dict = {
		  key1': 'value1',
		  key2': 'value2',
		  key3': 'value3',
		  ...
}

Alternatively, we can construct a dictionary using the built-in dict() function and passing one or more key-value pairs:

# Creating a dictionary with inital key-value pairs
d = dict(
		 key1 = value1,
		 key2 = value2,
		 key3 = value3,
		 ...
)

# Creating a dictionary with key-value pairs
d = dict([
		  (key1, value1),
		  (key2, value2),
		  (key3, value3),
		  ...
])

Clearing a Dictionary

To clear all the entries in a dictionary:

d.clear() # Deletes all entries.

This returns an empty dictionary.

Powered by Forestry.md