# Basic dictionary syntax
my_dict = {
"key1": "value1",
"key2": "value2"
}
{}
or the dict()
method.# Empty dictionary
empty_dict = {}
print(empty_dict)
# Dictionary with key-value pairs
dict1 = {"color": "pink", "shape": "square"}
print(dict1)
# Using the dict() method
dict2 = dict(color="blue", shape="circle")
print(dict2)
# Duplicate keys example
dict_example = {"color": "pink", "color": "red"}
print(dict_example) # Output: {'color': 'red'}
Note: Dictionary keys are case-sensitive, so"Color"
and"color"
are treated as different keys.
update()
Method:update()
method is ideal for adding multiple key-value pairs or merging dictionaries.# Adding elements to an empty dictionary
dict1 = {}
dict1.update({"color": "blue", "shape": "round"})
print(dict1)
# Merging dictionaries
dict2 = {"size": "small"}
dict1.update(dict2)
print(dict1)
# Adding a single key-value pair
dict1["length"] = "14cm"
print(dict1)
# Accessing a value
dict1 = {"color": "pink", "shape": "square"}
print(dict1["shape"]) # Output: square
get()
Method:get()
method is safer as it avoids errors if the key is missing.# Accessing a value using get()
print(dict1.get("shape")) # Output: square
print(dict1.get("size", "Key not found")) # Output: Key not found
# Modifying a value
dict1 = {"color": "pink", "shape": "square"}
dict1["color"] = "blue"
print(dict1) # Output: {'color': 'blue', 'shape': 'square'}
pop()
Method:# Using pop()
dict1 = {"color": "pink", "shape": "square"}
dict1.pop("color")
print(dict1) # Output: {'shape': 'square'}
del
Statement:# Deleting a key-value pair
del dict1["shape"]
print(dict1) # Output: {}
# Deleting the entire dictionary
del dict1
clear()
Method:# Using clear()
dict1 = {"color": "pink", "shape": "square"}
dict1.clear()
print(dict1) # Output: {}
Method | Description |
---|---|
keys() | Returns a view object of all the keys. |
values() | Returns a view object of all the values. |
items() | Returns a view object of key-value pairs. |
pop() | Removes a specified key-value pair. |
popitem() | Removes the last inserted key-value pair. |
clear() | Clears all elements in the dictionary. |
update() | Adds or updates key-value pairs. |