Python programs dictionary functions
# Create a dictionary
student = {'name': 'John', 'age': 25, 'grade': 'A'}
# Accessing values
print("Name:", student['name'])
print("Age:", student['age'])
print("Grade:", student['grade'])
# Create a dictionary
student = {'name': 'John', 'age': 25}
# Add new key-value pair
student['grade'] = 'A'
# Update value for existing key
student['age'] = 26
print("Updated Dictionary:", student)
# Create a dictionary
student = {'name': 'John', 'age': 25, 'grade': 'A'}
# Delete a key-value pair
del student['grade']
# Clear all elements from the dictionary
# student.clear()
print("Updated Dictionary:", student)
# Create a dictionary
student = {'name': 'John', 'age': 25, 'grade': 'A'}
# Iterate over keys
print("Keys:")
for key in student.keys():
print(key)
# Iterate over values
print("\nValues:")
for value in student.values():
print(value)
# Iterate over key-value pairs
print("\nKey-Value Pairs:")
for key, value in student.items():
print(key, ":", value)
# Create a dictionary
student = {'name': 'John', 'age': 25}
# Check if a key exists
if 'grade' in student:
print("Grade:", student['grade'])
else:
print("Grade key does not exist")
# Using get() method
print("Grade:", student.get('grade', 'Not found'))
No comments:
Post a Comment