Create a Dictionary in Python: {}, dict(), Dict Comprehensions

Modified: | Tags: Python, Dictionary

In Python, you can create a dictionary (dict) with curly brackets {}, dict(), and dictionary comprehensions.

For more information about dictionaries, how to add and remove items, and how to check for their existence, see the following articles.

Create a dictionary with curly brackets {}

Specify keys and values

To create a dictionary, write the key and value as key: value inside curly brackets {}.

{key: value, key: value, ...}
d = {'k1': 1, 'k2': 2, 'k3': 3}
print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}

Duplicate keys cannot be registered in the dictionary. If the same key is specified, its value is overwritten.

d = {'k1': 1, 'k2': 2, 'k3': 3, 'k3': 300}
print(d)
# {'k1': 1, 'k2': 2, 'k3': 300}

Merge multiple dictionaries

Since Python 3.5, you can use the syntax {**d1, **d2}.

You can create a new dictionary by merging two dictionaries, as shown in the example below. The original dictionaries remain unchanged.

d1 = {'k1': 1, 'k2': 2}
d2 = {'k3': 3, 'k4': 4}

d = {**d1, **d2}
print(d)
# {'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4}

print(d1)
# {'k1': 1, 'k2': 2}

print(d2)
# {'k3': 3, 'k4': 4}

This syntax also works with key: value.

print({**d1, **d2, 'k5': 5})
# {'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4, 'k5': 5}

You can merge three or more dictionaries.

d3 = {'k5': 5, 'k6': 6}

print({**d1, **d2, **d3})
# {'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4, 'k5': 5, 'k6': 6}

If the same key is specified, its value is overwritten.

d4 = {'k1': 100, 'k3': 300}

print({**d1, **d2, **d3, **d4, 'k5': 500})
# {'k1': 100, 'k2': 2, 'k3': 300, 'k4': 4, 'k5': 500, 'k6': 6}

To create a new dictionary from multiple dictionaries in earlier versions, use dict(**d1, **d2) as described below.

Since Python 3.9, you can merge multiple dictionaries with the | operator. See the following article for more details.

Create a dictionary with dict()

You can create a dictionary with dict().

There are several ways to specify arguments.

Use keyword arguments

You can use the keyword argument key=value.

d = dict(k1=1, k2=2, k3=3)
print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}

In this case, keys must be valid identifiers in Python. They cannot start with a number or contain symbols other than _.

If the same key is specified, an error is raised.

# d = dict(k1=1, k2=2, k3=3, k3=300)
# SyntaxError: keyword argument repeated: k3

Use a list of key-value pairs

You can also specify a list of key-value pairs, each as a tuple (key, value).

d = dict([('k1', 1), ('k2', 2), ('k3', 3)])
print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}

Any iterable containing key-value pairs can be used, such as a list of tuples or a tuple of lists.

d = dict((['k1', 1], ['k2', 2], ['k3', 3]))
print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}

In this case, no error occurs even if the keys are duplicated. The latter value overwrites the previous one.

d = dict([('k1', 1), ('k2', 2), ('k3', 3), ('k3', 300)])
print(d)
# {'k1': 1, 'k2': 2, 'k3': 300}

Use a list of keys and a list of values

By using zip(), you can create a dictionary from a list of keys and a list of values.

keys = ['k1', 'k2', 'k3']
values = [1, 2, 3]

d = dict(zip(keys, values))
print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}

In this case, no error occurs even if the keys are duplicated. The latter value overwrites the previous one. Examples are omitted here.

Use another dictionary

When another dictionary is passed as an argument to dict(), a new dictionary with the same keys and values is created.

d_other = {'k10': 10, 'k100': 100}

d = dict(d_other)
print(d)
# {'k10': 10, 'k100': 100}

In this case, a shallow copy is created. If the value contains mutable objects like dictionaries or lists, they will be the same object in both the original and the copy. Therefore, when one is updated, the other will also be updated.

An error is raised if multiple dictionaries are passed to dict().

d1 = {'k1': 1, 'k2': 2}
d2 = {'k3': 3, 'k4': 4}

# d = dict(d1, d2)
# TypeError: dict expected at most 1 arguments, got 2

As mentioned above, you can pass keys and values as keyword arguments (using key=value syntax) to dict(). By prefixing dictionaries with ** when calling dict(), you can pass each key-value pair as a separate keyword argument.

d = dict(**d1, **d2)
print(d)
# {'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4}

Note that duplicate keys cause an error in this case.

As mentioned above, starting with Python 3.5, you can use {**d1, **d2}, and in this case, duplicate keys are not a problem.

d1 = {'k1': 1, 'k2': 2}
d2 = {'k1': 100, 'k3': 3}

# d = dict(**d1, **d2)
# TypeError: dict() got multiple values for keyword argument 'k1'

d = {**d1, **d2}
print(d)
# {'k1': 100, 'k2': 2, 'k3': 3}

Create a dictionary with dictionary comprehensions

In the same way that lists can be created with list comprehensions, dictionaries can be created with dictionary comprehensions.

Dictionary comprehensions are enclosed in curly brackets {} instead of square brackets [].

{key: value for variable_name in iterable}

You can specify any expression for key and value.

l = ['Alice', 'Bob', 'Charlie']

d = {s: len(s) for s in l}
print(d)
# {'Alice': 5, 'Bob': 3, 'Charlie': 7}

To create a dictionary from a list of keys and a list of values, you can use zip(), just as you would with dict().

keys = ['k1', 'k2', 'k3']
values = [1, 2, 3]

d = {k: v for k, v in zip(keys, values)}
print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}

You can also use conditional branching with if in dictionary comprehensions.

If you want to create a dictionary simply from a list of keys and a list of values, you can use dict() as described above. However, if you want to manipulate values or select elements according to conditions, dictionary comprehensions are useful.

d = {k: v for k, v in zip(keys, values) if v % 2 == 1}
print(d)
# {'k1': 1, 'k3': 3}

Dictionary comprehensions can also be used to create a new dictionary by extracting or removing items from an existing dictionary that meet specific conditions.

d = {'apple': 1, 'banana': 10, 'orange': 100}

dc = {k: v for k, v in d.items() if v % 2 == 0}
print(dc)
# {'banana': 10, 'orange': 100}

dc = {k: v for k, v in d.items() if v % 2 == 1}
print(dc)
# {'apple': 1}

dc = {k: v for k, v in d.items() if k.endswith('e')}
print(dc)
# {'apple': 1, 'orange': 100}

dc = {k: v for k, v in d.items() if not k.endswith('e')}
print(dc)
# {'banana': 10}

dc = {k: v for k, v in d.items() if v % 2 == 0 and k.endswith('e')}
print(dc)
# {'orange': 100}

Use the items() method of dict to extract keys and values.

Related Categories

Related Articles