Dictionary:
In Python, a dictionary is a built-in data type used to store collections of data in a key-value pair format. Dictionaries are unordered, mutable, and can contain elements of different data types. Each element in a dictionary is accessed by its key rather than by an index, making dictionaries extremely flexible and efficient for retrieving, updating, and managing data.
Syntax:
my_dictionary = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
Example:
info = {'name':'Abdullah', 'cgpa':2.57, 'profession':'student'}
print("Dictionary:", info)
Output:
Check Data Type:
info = {'name':'Abdullah', 'cgpa':2.57, 'profession':'student'}
print(type(info))
Output:
Access a Value:
info = {'name':'Abdullah', 'cgpa':2.57, 'profession':'student'}
print("Name:", info['name'])
print("Profession:", info['profession'])
print("CGPA:", info['cgpa'])
To access a value from the dictionary simply write the dictionary name with the key as dictionary-name['key-name']
.
Output:
Modifying a Value:
info = {'name':'Abdullah', 'cgpa':2.57, 'profession':'student'}
print("Before Modification:", info)
info['profession'] = 'CS Student'
print("After Modification:", info)
Output:
Adding a New Key-Pair Value:
info = {'name':'Abdullah', 'cgpa':2.57, 'profession':'student'}
print("Before Addition:", info)
info['gender'] = 'male'
print("After Addition:", info)
Output:
Deleting a Key-Pair Value:
info = {'name':'Abdullah', 'cgpa':2.57, 'profession':'student'}
print("Before Deletion:", info)
del info['profession']
print("After Deletion:", info)