In Python, a dictionary (also called a "dict") is a collection of items that are stored as key-value pairs. Dictionaries are represented using curly braces, and the items are separated by commas. The keys and values in a dictionary are separated by a colon. Here is an example of a dictionary in Python:
person = {'name': 'John', 'age': 30, 'gender': 'male'}
In this example, the keys are 'name', 'age', and 'gender', and the corresponding values are 'John', 30, and 'male', respectively.
You can access the items in a dictionary by referring to the key. For example, you can access the value for the 'name' key like this:
name = person['name'] # name is 'John'
You can also modify the values in a dictionary by assigning a new value to a specific key. For example:
person['age'] = 35
This would change the value for the 'age' key from 30 to 35.
You can add new items to a dictionary by assigning a value to a new key:
person['city'] = 'New York'
You can remove items from a dictionary using the del
keyword:
del person['city']
You can also use various built-in functions and methods to work with dictionaries in Python. Some common ones include:
len()
: returns the number of items in a dictionarykeys()
: returns a list of the keys in a dictionaryvalues()
: returns a list of the values in a dictionaryitems()
: returns a list of the key-value pairs in a dictionary
For example:
# Get the number of items in the dictionary
num_items = len(person)
# Get the keys in the dictionary
keys = person.keys()
# Get the values in the dictionary
values = person.values()
# Get the key-value pairs in the dictionary
items = person.items()
You can also use loops and conditional statements to work with dictionaries in Python. For example, you can use a for
loop to iterate over the keys in a dictionary and perform a specific action on each key-value pair. You can also use an if
statement to check the value of a key and perform different actions based on the value.
For more information on dictionaries in Python, you can refer to the Python documentation or search online for tutorials and examples.
0 댓글