set&dict
Sets and dictionaries are unordered collections of items.
They serve different purposes due to their unique properties.
In Common Unordered
- Both sets and dictionaries do not have a defined order for their elements. This means you cannot rely on the order of insertion or any other order when iterating over them. The elements are stored in a way that makes retrieval efficient, but the order of elements is not guaranteed.
In Common Mutability
- meaning you can add or remove elements from a set.
- Dictionaries are mutable as well, allowing for the addition, removal, or modification of key-value pairs.
# Adding elements to a set
my_set.add(6)
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
# Adding a new key-value pair to a dictionary
my_dict['d'] = 4
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
differences between sets and dictionaries:
Accessing Elements:
- Sets are accessed by iterating over the set or by checking for membership.
- Dictionaries are accessed using keys.
# Accessing elements in a set
for element in my_set:
print(element) # Output: 1, 2, 3, 4, 5
# Accessing elements in a dictionary
print(my_dict['a']) # Output: 1
About accessing dictionaries
Sets:
- A set is a collection of unique elements. Each element in a set must be unique, and duplicate elements are automatically removed.
- Sets are unordered, meaning the elements are not stored in any particular order.
- Sets are typically used when you want to perform operations like intersection, union, and difference between collections.
Example
# Creating a set
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
Dictionaries:
- A dictionary is a collection of key-value pairs. Each element in a dictionary consists of a key and its associated value.
- Dictionaries are unordered as well, but from Python 3.7 onwards, insertion order of keys is preserved. In Python 3.6 and earlier, dictionaries are unordered.
- Keys in a dictionary must be unique, but the values can be duplicated.
- Dictionaries are useful for storing and retrieving data based on some unique identifier (the key).
Example
# Creating a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
Data Type | Content Type | Sequence | Mutable | defined Order |
---|---|---|---|---|
string | characters | yes | no | |
list | anything | yes | yes | |
tuple | anything | yes | no | |
range | integers | yes | no | |
set | immutable items | no | yes | unordered collections |
dictionary | immutable items | no | yes | unordered collections |