dict()

Creates a dictionary from key-value pairs or keyword arguments.

Returns
A new dictionary.
On this page

Example

#
Python
print(dict(html=11, css=9))
print(dict([("python", 12), ("react", 16)]))

courses = ["HTML", "Python"]
modules = [11, 12]
print(dict(zip(courses, modules)))
Resultsaved result, you can check it
{'html': 11, 'css': 9}
{'python': 12, 'react': 16}
{'HTML': 11, 'Python': 12}

Definition and usage

#

The dict() function creates a dictionary. With no arguments it gives an empty dictionary, with keyword arguments it builds one from names and values (dict(html=11, css=9)), and from a list of pairs it turns each pair into a key and a value.

It is often combined with zip(): dict(zip(keys, values)) creates a dictionary from two lists.

Dictionaries in Python keep the order in which keys were added. Keys must be immutable (strings, numbers, tuples), while values can be anything.

Syntax

#
Syntax
dict()
dict(key=value, …)
dict(pairs)

Parameters

#
  • mapping / iterable / **kwargs

    optional

    Key-value pairs, a dictionary, or keyword arguments.

Good practices

#
  • Create an empty dictionary with {}. dict() is mainly useful for converting pairs and for keyword arguments.
  • Keyword arguments in dict(...) must be valid variable names, so a key containing a space needs the curly-brace syntax instead.

Related entries

#

Spotted a mistake or missing an example? Write to us.