In Python, you can create a dictionary by enclosing a comma-separated list of key-value pairs in curly braces
{}. Each key-value pair consists of a key, followed by a colon
:, and then the corresponding value.
Here's an example of creating a dictionary that maps names to ages:
my_dict = {'Alice': 25, 'Bob': 30, 'Charlie': 35}
You can also create an empty dictionary and add key-value pairs to it later using square bracket notation
[]:
Dictionaries in Python are used to store data values in a key: value pair, unlike other data types that can hold only single values as an element. It is a collection that is ordered, and mutable and does not allow for duplicate values.
The values can be of any data type and can be duplicated, however, the keys cannot be duplicated and must be
immutable. The keys are also case-sensitive.
We can add elements to a dictionary by using a new index key and assigning a value to it.
dict["nationality"] = "UK"
The update() method can be used to update the items within a dictionary. If the item does not exist, it will be added.
dict.update({"age": 28})
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In Python, you can create a dictionary by enclosing a comma-separated list of key-value pairs in curly braces {}. Each key-value pair consists of a key, followed by a colon :, and then the corresponding value.
Here's an example of creating a dictionary that maps names to ages:
You can also create an empty dictionary and add key-value pairs to it later using square bracket notation []:
You can also use the dict() constructor to create a dictionary from a list of tuples, where each tuple represents a key-value pair:
Once you have created a dictionary, you can access its values by using square bracket notation to specify the key:
Dictionaries in Python are used to store data values in a key: value pair, unlike other data types that can hold only single values as an element. It is a collection that is ordered, and mutable and does not allow for duplicate values.
We can create a dictionary in Python as follows:
The values can be of any data type and can be duplicated, however, the keys cannot be duplicated and must be immutable. The keys are also case-sensitive.
We can add elements to a dictionary by using a new index key and assigning a value to it.
The update() method can be used to update the items within a dictionary. If the item does not exist, it will be added.