Dictionary
Dictionary
Creating a Dictionary:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
empty_dict = {}
Accessing Elements:
print(my_dict['name']) # Output: John
print(my_dict.get('age')) # Output: 30
Modifying a Dictionary
my_dict['age'] = 35 # Update value
my_dict['gender'] = 'Male' # Add new key-value pair
Removing Elements:
del my_dict['city'] # Remove a specific key-value pair
my_dict.pop('age') # Remove and return the value associated with the given
key
my_dict.clear() # Remove all items
Dictionary Methods:
# Getting keys and values
print(my_dict.keys())
print(my_dict.values())
# Checking membership
print('name' in my_dict) # Output: True
# Length of dictionary
print(len(my_dict))
Dictionary Iteration
# Iterating over keys
for key in my_dict:
print(key, my_dict[key])
3) fromkeys(seq[, value]): Returns a new dictionary with keys from seq and
value set to value
keys = ['a', 'b', 'c']
values = 0
new_dict = dict.fromkeys(keys, values)
print(new_dict) # Output: {'a': 0, 'b': 0, 'c': 0}
: This creates a new dictionary with keys from the given sequence keys and
assigns the same value (0) to each key.
4) get(key[, default]): Returns the value for the specified key, or default if the
key is not found.
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.get('b')
print(value) # Output: 2
This retrieves the value associated with the key 'b' from the dictionary. If the
key is not found, it returns the default value 0.
6) keys(): Returns a view object that displays a list of all the keys in the
dictionary.
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = my_dict.keys()
print(keys) # Output: dict_keys(['a', 'b', 'c'])
This returns a view object containing all the keys in the dictionary.
9)pop(): In Python, dictionaries have a pop() method that allows you to remove
an item from the dictionary based on its key and returns the corresponding value