Dictionaries are a fundamental data structure in Python used to store data values mapped to unique keys. Dictionaries provide a flexible way to store and organize data, making them useful for a wide range of programming tasks. In this comprehensive guide, we will explore the various methods to create dictionaries in Python, with example code snippets and detailed explanations.
Table of Contents
Open Table of Contents
- What are Dictionaries in Python?
- Creating an Empty Dictionary
- Creating a Dictionary with Initial Values
- Creating a Dictionary from Sequences
- Creating a Dictionary from Keys and Values Separately
- Creating a Dictionary from Keyword Arguments
- Copying and Nested Dictionaries
- Dictionaries vs Lists vs Tuples
- In-place vs Copy in Dictionaries
- Dictionaries vs Objects
- Dictionary Use Cases
- Summary
What are Dictionaries in Python?
A dictionary in Python is an unordered collection of key-value pairs used to store data values like a map. Dictionaries consist of keys and values where:
-
Key - An immutable data type that is used to uniquely identify the values. Keys are used to index and lookup values in a dictionary. Keys must be unique within the dictionary. Immutable built-in types like integers, floats, strings, tuples can be used as keys.
-
Value - A mutable data type that is stored in the dictionary. Values can be accessed and updated using their corresponding key. Any Python data type like lists, sets, dictionaries etc. can be used as values.
Dictionaries are denoted by curly braces {}
and have key-value pairs separated by colons :
. For example:
dict_1 = {'key1': 'value1', 'key2': 'value2'}
Here key1
, key2
are the keys and 'value1'
, 'value2'
are the values stored.
Dictionaries are dynamic, allowing elements to be added or removed. They can grow and shrink in size. The major characteristics of dictionaries are:
-
Unordered: Elements stored in a dictionary are unordered. The order in which items are inserted is not preserved.
-
Mutable: Dictionaries are mutable, meaning they can be changed after creation. New key-value pairs can be added, values can be updated, and key-value pairs can be removed after dictionary creation.
-
Key uniqueness: Dictionary keys must be unique within one dictionary. No two identical keys are allowed. Duplicate keys will overwrite existing values.
-
Nesting: Dictionaries can be nested within other compound data types like lists, tuples, sets, and other dictionaries.
These properties make dictionaries a versatile data structure ideal for many real-world use cases like storing user profiles in applications, caching data in web development, and counting word frequencies in text.
Creating an Empty Dictionary
An empty dictionary that has no elements can be created in two ways:
- Using a pair of curly braces:
empty_dict = {}
- Using the dict() constructor:
empty_dict = dict()
For example:
empty_dict_1 = {}
empty_dict_2 = dict()
print(empty_dict_1)
print(empty_dict_2)
Output:
{}
{}
The {}
and dict()
methods are equivalent and produce an empty dictionary object that we can add elements to.
Creating a Dictionary with Initial Values
To initialize a dictionary with values, we need to provide the key-value pairs inside curly braces {}
separated by commas.
The key-value pairs are defined as key: value
pairs within the curly braces. For example:
dict_1 = {'key1': 'value1', 'key2': 'value2'}
Here, 'key1'
and 'key2'
are the keys while 'value1'
and 'value2'
are the values referenced by those keys.
We can also initialize a dictionary with values using the dict()
constructor along with a sequence of key-value pairs as arguments.
For example:
dict_2 = dict(key1='value1', key2='value2')
The dict()
constructor takes the comma-separated key-value pairs and converts them into a dictionary.
Let’s look at some more examples of creating dictionaries with initial values:
# dict with three key-value pairs
dict_1 = {'name': 'John', 'age': 28, 'role': 'Developer'}
# dict with numeric keys and values of different data types
dict_2 = {1: 'one', 2: [1,2], 3: {'a':'apple', 'b':'ball'}}
# from sequence of key-value pairs
dict_3 = dict(country='India', capital='Delhi', population=1350000000)
print(dict_1)
print(dict_2)
print(dict_3)
Output:
{'name': 'John', 'age': 28, 'role': 'Developer'}
{1: 'one', 2: [1, 2], 3: {'a': 'apple', 'b': 'ball'}}
{'country': 'India', 'capital': 'Delhi', 'population': 1350000000}
This demonstrates how we can create dictionaries with different types of keys and values.
Creating a Dictionary from Sequences
We can also create dictionaries from sequences of key-value pairs. Let’s look at some examples:
From a List of Tuples
If we have a list of tuples containing key-value pairs, we can use the dict()
constructor to directly convert them into a dictionary:
dict_from_list = dict([('key1', 1), ('key2', 2), ('key3', 3)])
print(dict_from_list)
Output:
{'key1': 1, 'key2': 2, 'key3': 3}
From Two Lists
We can create a dictionary by passing two lists to dict()
- one for keys and one for values.
For example:
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dict_from_lists = dict(zip(keys, values))
print(dict_from_lists)
Output:
{'a': 1, 'b': 2, 'c': 3}
Here zip()
zips together the elements of the keys and values lists to create the key-value pairs.
From String Key-Value Pairs
We can use dict()
to create a dictionary from a string containing comma-separated key-value pairs:
dict_from_string = dict('a=1, b=2, c=3')
print(dict_from_string)
Output:
{'a': '1', 'b': '2', 'c': '3'}
This parses the string and adds each key-value pair to the dictionary.
Creating a Dictionary from Keys and Values Separately
We can create dictionaries by first defining keys and values separately as sequences and then zipping them:
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dict_from_kv = dict(zip(keys, values))
print(dict_from_kv)
Output:
{'a': 1, 'b': 2, 'c': 3}
Here the zip()
function combines the keys and values into tuples, which dict()
then converts into key-value pairs.
We can also unpack keys and values from two lists directly into a dictionary using dict comprehension:
keys = ['x','y','z']
values = [1,2,3]
dict_comp = {k:v for k, v in zip(keys, values)}
print(dict_comp)
Output:
{'x': 1, 'y': 2, 'z': 3}
This provides a concise way to create dictionaries from sequences.
Creating a Dictionary from Keyword Arguments
We can use the **
operator to create a dictionary from keyword arguments.
For example:
dict_kwargs = dict(a=1, b=2, c=3)
print(dict_kwargs)
Output:
{'a': 1, 'b': 2, 'c': 3}
This unpacks the keyword arguments into key-value pairs for the dictionary.
We can also use the double star **
operator to unpack keyword arguments from another dictionary:
kwargs = {'a': 1, 'b': 2, 'c': 3}
dict_kwargs = dict(**kwargs)
print(dict_kwargs)
Output:
{'a': 1, 'b': 2, 'c': 3}
This provides a convenient way to clone or combine dictionaries.
Copying and Nested Dictionaries
When creating dictionaries, we need to be aware of copying and nesting behavior.
Copying Dictionaries
When assigning a dictionary to a new variable, a reference to the original dictionary is copied rather than a new copy. For example:
dict_1 = {'a':1, 'b':2}
dict_2 = dict_1
dict_2['b'] = 20
print(dict_1)
print(dict_2)
Output:
{'a': 1, 'b': 20}
{'a': 1, 'b': 20}
Changing dict_2
also affects dict_1
because they point to the same dictionary.
To create a real copy, we need to explicitly copy the dictionary:
dict_1 = {'a':1, 'b':2}
dict_2 = dict_1.copy()
dict_2['b'] = 20
print(dict_1)
print(dict_2)
Output:
{'a': 1, 'b': 2}
{'a': 1, 'b': 20}
Now changes to dict_2
do not affect the original dict_1
.
Nested Dictionaries
Dictionaries can contain other dictionaries to create nested or multi-level dictionaries:
dict_nested = {
'dict_1': {'key_a': 1, 'key_b': 2},
'dict_2': {'key_x': 100, 'key_y': 200}
}
print(dict_nested)
Output:
{'dict_1': {'key_a': 1, 'key_b': 2}, 'dict_2': {'key_x': 100, 'key_y': 200}}
This nested dictionary contains the dictionaries 'dict_1'
and 'dict_2'
under the keys 'dict_1'
and 'dict_2'
respectively.
We need to use keys to access the inner dictionaries before accessing their keys and values.
Dictionaries vs Lists vs Tuples
Python provides several built-in data structures, but dictionaries have specific properties that make them useful in different scenarios compared to lists or tuples.
-
Lists - Ordered, indexed by integers, mutable sequences allowing duplicate elements. Useful for ordered storage and access.
-
Tuples - Ordered, indexed by integers, immutable sequences allowing duplicate elements. Useful for fixed data and key-value pairs.
-
Dictionaries - Unordered, indexed by keys which can be different types, mutable key-value stores with unique keys. Useful for lookups by key and managing related data.
Some key differences:
-
Dictionaries allow accessing values directly by their unique key, while lists and tuples require searching the sequence.
-
Dictionaries are optimized for lookup speed by key, while lists and tuples are optimized for fast positional access.
-
Dictionaries can store any mutable data type as value, unlike lists and tuples which have strict element type.
-
Dictionaries have unique keys while lists and tuples can contain duplicate elements.
So in summary:
-
Use dictionaries for key-value associations, lookups by key, and managing complex data.
-
Use lists for ordered storage and access by index position.
-
Use tuples for fixed data that won’t change.
This comparison helps us select the right data structure for a particular programming task.
In-place vs Copy in Dictionaries
Dictionaries in Python exhibit two kinds of operations - in-place and copy:
-
In-place - The operation modifies the original dictionary object directly. e.g. adding or removing dictionary elements.
-
Copy - The operation returns a new dictionary copy leaving the original dictionary unchanged. e.g.
dict.copy()
This is an important distinction when writing Python code that handles dictionaries.
For example, methods like pop()
, popitem()
, clear()
, update()
perform in-place operations modifying the dictionary:
dict_1 = {'a': 1, 'b':2, 'c':3}
dict_1.pop('a')
print(dict_1)
dict_1.popitem()
print(dict_1)
dict_1.clear()
print(dict_1)
Output:
{'b': 2, 'c': 3}
{'b': 2}
{}
While methods like copy()
and dictionary comprehensions create a new dictionary copy:
dict_2 = {'x': 1, 'y': 2}
dict_copy = dict_2.copy()
dict_comp = {k: v for k, v in dict_2.items()}
print(dict_2)
print(dict_copy)
print(dict_comp)
Output:
{'x': 1, 'y': 2}
{'x': 1, 'y': 2}
{'x': 1, 'y': 2}
Being aware of in-place vs copy operations helps avoid inadvertently modifying dictionaries when copying is needed.
Dictionaries vs Objects
Python dictionaries and objects, i.e. instance of classes, have some similarities in key-value storage but also important differences:
Similarities
-
Both can store data values that are accessible by keys like attribute names or dictionary keys.
-
Both are mutable, allowing adding/updating/deleting elements after creation.
-
Both can represent real-world entities with a collection of related attributes.
Differences
-
Dictionaries are more flexible allowing any hashable keys like strings or numbers. Object attributes have naming restrictions.
-
Dictionaries are optimized for fast data access and lookups. Objects provide additional behavior like methods.
-
Dictionaries have no defined structure or schema. Objects have defined attributes and methods.
-
Objects allow data encapsulation and abstraction. Dictionaries are directly accessible.
-
Objects allow inheritance to extend functionality. Dictionaries have no inheritance.
So in summary:
-
Use dictionaries for simple key-value data stores optimized for access speed.
-
Use objects for modeling complex entities with custom behavior and data encapsulation.
Understanding these key differences helps decide when to use a dictionary versus defining a class instance.
Dictionary Use Cases
Some common use cases where dictionaries are very useful in Python programming:
- Storing configuration or settings for code, e.g. default values
- Caching data from costly operations or external calls
- Counting word frequencies or other metrics from text
- Maintaining user profiles in a web application
- Passing keyword arguments to functions using
**kwargs
- Keeping metadata or properties associated with items
- Creating lookup tables for efficient searching
Dictionaries provide fast insertion, update and lookup of data by unique keys making them very versatile for many programming tasks.
Summary
To summarize, dictionaries are a critical data structure in Python used to store data values mapped to keys. The major points covered include:
- Dictionaries are unordered, mutable collections of key-value pairs
- Dictionaries are created using
{}
ordict()
constructor - Keys are used to lookup and index values in a Python dictionary
- Dictionaries can be created from sequences of key-value pairs
- Dictionaries vs lists vs tuples - each have different properties and use cases
- Performing in-place operations vs copies on dictionaries
- Dictionaries vs objects for key-value data storage
- Common dictionary use cases and patterns
Dictionaries provide an indispensable data structure for creating effective programs. Mastering dictionary operations like creation, updating, lookups is essential to leverage their power for Python programming tasks.