Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- """
- # Creating a dictionary
- my_dict = {
- 'name': 'Alice',
- 'age': 25,
- 'city': 'New York'
- }
- # Accessing elements
- name = my_dict['name'] # Access the value associated with the key 'name'
- # Modifying elements
- my_dict['age'] = 26 # Change the value associated with the key 'age'
- # Adding elements
- # Removing elements
- del my_dict['city'] # Remove the key-value pair with the key 'city'
- removed_value = my_dict.pop('email') # Remove and return the value associated with 'email'
- last_item = my_dict.popitem() # Remove and return the last inserted key-value pair (Python 3.7+)
- # Checking for keys
- has_name = 'name' in my_dict # Check if the key 'name' is in the dictionary
- has_city = 'city' in my_dict # Check if the key 'city' is in the dictionary
- # Getting the value of a key with a default
- age = my_dict.get('age', 0) # Get the value for 'age', return 0 if 'age' is not found
- country = my_dict.get('country', 'Unknown') # Get the value for 'country', return 'Unknown' if not found
- # Iterating through a dictionary
- for key in my_dict:
- print(key, my_dict[key]) # Print each key-value pair
- for key, value in my_dict.items():
- print(key, value) # Print each key-value pair using items()
- # Iterating through keys and values separately
- for key in my_dict.keys():
- print(key) # Print each key
- for value in my_dict.values():
- print(value) # Print each value
- # Dictionary comprehension
- squared_numbers = {x: x**2 for x in range(1, 6)} # Create a dictionary with numbers and their squares
- # Merging dictionaries
- another_dict = {'country': 'USA', 'gender': 'Female'}
- my_dict.update(another_dict) # Merge another_dict into my_dict
- # Clearing the dictionary
- my_dict.clear() # Remove all key-value pairs from the dictionary
- # Dictionary methods
- keys = my_dict.keys() # Get a view of all keys
- values = my_dict.values() # Get a view of all values
- items = my_dict.items() # Get a view of all key-value pairs
- # Copying a dictionary
- copied_dict = my_dict.copy() # Create a shallow copy of the dictionary
- # Nested dictionaries
- nested_dict = {
- 'person1': {'name': 'Alice', 'age': 25},
- 'person2': {'name': 'Bob', 'age': 30}
- }
- person1_name = nested_dict['person1']['name'] # Accessing nested dictionary elements
Advertisement
Add Comment
Please, Sign In to add comment