Python dict
Created By: chatGPT
In Python, a dictionary is a collection of key-value pairs. It's used to store data values like a map, which, unlike lists, allows you to retrieve data by a unique key rather than an index. Here’s how you can create a dictionary:
my_dict = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}
You can access the values in a dictionary by referencing their keys. For example, to get the age of the person, you would use:
age = my_dict['age'] # This will return 30
Dictionaries in Python are dynamic, meaning you can add or remove key-value pairs at any time. To add a new key-value pair, you simply assign a value to a new key:
my_dict['job'] = 'Engineer' # Adds a new key 'job' with value 'Engineer'
To remove a key-value pair, you can use the del statement or the pop() method. The pop method not only removes the key but also returns the value associated with that key. Here’s how it works:
del my_dict['city'] # Removes the key 'city'
job = my_dict.pop('job') # Removes the 'job' key and returns 'Engineer'
You can also iterate through a dictionary using a for loop. You might want to access only the keys, only the values, or both. Here are examples for each scenario:
for key in my_dict:
print(key) # Prints all keys
for value in my_dict.values():
print(value) # Prints all values
for key, value in my_dict.items():
print(f'{key}: {value}') # Prints key-value pairs
Dictionaries can also be nested, meaning you can have another dictionary as a value in a key-value pair. Here’s how a nested dictionary looks:
nested_dict = {
'person1': {
'name': 'Alice',
'age': 30
},
'person2': {
'name': 'Bob',
'age': 25
}
}