note.nkmk.me

Create a dictionary in Python ({}, dict(), dict comprehensions)

Posted: 2021-09-14 / Modified: 2021-09-18 / Tags: Python, Dictionary

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

This article describes the following contents.

  • Create a dictionary with curly brackets {}
    • Specify keys and values
    • Merge multiple dictionaries
  • Create a dictionary with dict()
    • Use keyword arguments
    • With a list of key/value pairs
    • With a list of keys and a list of values
    • With another dictionary
  • Create a dictionary with dictionary comprehensions

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

Sponsored Link

Create a dictionary with curly brackets {}

Specify keys and values

You can create a dictionary by writing the key and value as key: value in curly brackets {}.

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

Since the same key cannot be registered in the dictionary, if the same key is specified, it 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 write like {**d1, **d2}.

You can create a new dictionary by merging two dictionaries, as follows. The original dictionaries are not updated.

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}

It can also be used with key: value.

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

You can specify 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, it 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}

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

Since Python 3.9, it is possible to merge multiple dictionaries with the | operator. See the following article for details.

Create a dictionary with dict()

You can create a dictionary with dict().

There are several ways to specify arguments.

Use keyword arguments

It can be specified with the keyword argument key=value.

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

In this case, only strings that are valid as variable names can be specified as keys. It cannot start with a number or contain any symbols other than _.

If the same key is specified, an error raises.

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

With a list of key/value pairs

It can also be specified with a list of key-value pairs (such as a tuple (key, value)).

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

It can be any iterable whose elements are iterables with a key and value. For example, it can be specified as a tuple of lists or a list of lists.

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

In this case, there is no error even if the keys are duplicated. It is overwritten by the value of the later item.

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

With a list of keys and a list of values

Using zip(), you can create a dictionary from a list of keys and a list of values. Not only lists but also tuples can be used.

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

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

See the following article about zip().

In this case, too, no error raises even if there are duplicate keys, although no example is shown here. It is overwritten by the later value.

If you want to process values in a list or select elements based on conditions, use dictionary comprehensions described below.

With another dictionary

If another dictionary is specified as the argument of dict(), a 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 such as dictionaries or lists, they are the same object in the original and the copy, so when one is updated, the other is also updated.

An error occurs if multiple dictionaries are specified as an argument of 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, dict() allows you to specify keys and values as keyword arguments (key=value), so you can add ** to the dictionary and pass each item as a keyword argument.

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

Note that duplicate keys will cause an error in this case.

As mentioned above, it is also possible to use {**d1, **d2} from Python 3.5, in which 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}
Sponsored Link

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.

The difference from list comprehensions is that dictionary comprehensions are enclosed in {} instead of [], and keys and values are specified.

{key: value for variable_name in iterable}

Any expression can be specified 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, use zip() as in the case of 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}

Conditional branching by if is also possible with dictionary comprehensions.

If you want to create a dictionary simply from a list, you can use dict() as described above, but if you want to process 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}

It can also be used to create a new dictionary by extracting or removing items from an existing dictionary that meet the condition.

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}

The items() method of dict is used to extract keys and values .

Sponsored Link
Share

Related Categories

Related Articles