gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
create a dictionary python
- User
create a dictionary python
- Assistant
Sure! Here is an example of a dictionary in Python:
# Creating a dictionary named "my_dict" my_dict = { "name": "John", # key-value pairs "age": 25, "city": "New York" } # Accessing values from the dictionary print(my_dict["name"]) # Output: John print(my_dict["age"]) # Output: 25 print(my_dict["city"]) # Output: New York # Adding a new key-value pair to the dictionary my_dict["occupation"] = "Engineer" print(my_dict) # Output: {'name': 'John', 'age': 25, 'city': 'New York', 'occupation': 'Engineer'} # Updating a value in the dictionary my_dict["age"] = 30 print(my_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'occupation': 'Engineer'} # Deleting a key-value pair from the dictionary del my_dict["city"] print(my_dict) # Output: {'name': 'John', 'age': 30, 'occupation': 'Engineer'} # Clearing the entire dictionary my_dict.clear() print(my_dict) # Output: {}In this example, we've created a dictionary called "my_dict" with some key-value pairs. We can access values from the dictionary using the keys. We can also add, update, and delete key-value pairs in the dictionary, as well as clear the entire dictionary using the
clear()method.