Skip to content

Creating Dictionaries in Python - A Comprehensive Guide

Updated: at 04:34 AM

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?

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:

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:

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:

  1. Using a pair of curly braces:
empty_dict = {}
  1. 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.

Some key differences:

So in summary:

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:

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

Differences

So in summary:

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:

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 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.