Python Sets Dictionaries Notes
Python Sets Dictionaries Notes
Sets in Python
- A set is an unordered collection of unique items.
- Sets are defined using curly braces {} or using set().
- Example: my_set = {1, 2, 3}
- Duplicate elements are not allowed.
- No indexing in sets, use loops to access elements.
Example Code:
fruits = {'apple', 'banana', 'cherry'}
fruits.add('orange')
fruits.remove('banana')
for fruit in fruits:
print(fruit)
Dictionaries in Python
- A dictionary is a collection of key-value pairs.
- Defined using curly braces {} with key: value.
- Example: student = {'name': 'John', 'age': 18}
- Keys must be unique; values can be duplicated.
Example Code:
student = {'name': 'John', 'age': 18, 'grade': 'A'}
print(student['name'])
student['gender'] = 'Male'
student['grade'] = 'A+'
for key, value in student.items():
print(key, ':', value)