Python dict usage detailed explanation and examples

Python dict Usage Explained with Examples

Python dict Syntax and Examples

In Python, a dict is a data structure used to store key-value pairs, also known as a dictionary. Dictionaries can be used to store and access very large data sets, providing fast lookup and insertion operations.

Basic Dictionary Syntax
Dictionaries are denoted by curly braces ({}), with key-value pairs separated by colons (:). Keys must be unique, and values can be of any type. Here’s a simple dictionary example:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

Example 1:

person = {"name": "Tom", "age": 25, "gender": "male"}
print(person)

Output:

{"name": "Tom", "age": 25, "gender": "male"}

This example shows how to create a dictionary named person with three key-value pairs: name, age, and gender, with corresponding values: Tom, 25, and male. We can use the print function to output the entire dictionary.

Example 2:

fruits = {
"apple": 15,
"banana": 10,
"orange": 20
}

In this example, we create a dictionary named fruits containing three types of fruit and their corresponding quantities. The keys are the fruit names, and the values are the fruit quantities.

Example 3:

student = {
"id": "123456789",
"name": "Xiao Ming",
"grade": 9,
"scores": {
"math": 90,
"english": 80,
"chinese": 95
}
}

This example shows that a value in a dictionary can also be a dictionary. The value corresponding to the key scores in the student dictionary is a dictionary containing math, English, and Chinese scores.

The dictionary data structure is very common and useful in Python. You can access values in a dictionary by key, and you can also modify, add, or delete values by key. By using dictionaries, we can more conveniently organize and manipulate data.

Leave a Reply

Your email address will not be published. Required fields are marked *