Set vs Dictionary in Python: Key Differences and Usage
set in Python is an unordered collection of unique elements, while a dictionary stores key-value pairs with unique keys. Sets are used for membership tests and eliminating duplicates, whereas dictionaries map keys to values for fast lookup.Quick Comparison
Here is a quick side-by-side comparison of Python set and dictionary features.
| Feature | Set | Dictionary |
|---|---|---|
| Data Structure | Unordered collection of unique elements | Unordered collection of key-value pairs |
| Syntax | Curly braces with elements: {1, 2, 3} | Curly braces with key:value pairs: {'a': 1, 'b': 2} |
| Duplicates | Not allowed; elements are unique | Keys are unique; values can repeat |
| Access | Check if element exists | Access value by key |
| Use Case | Membership tests, removing duplicates | Mapping keys to values, fast lookup |
| Mutable | Yes, can add or remove elements | Yes, can add, update, or remove key-value pairs |
Key Differences
Sets are collections that only store unique items without any associated values. They are unordered, so you cannot access elements by position or key. Sets are great when you want to check if something exists or to remove duplicates from a list.
Dictionaries, on the other hand, store data as key-value pairs. Each key is unique and maps to a value, which can be any data type. This allows you to quickly find a value by its key, making dictionaries ideal for representing structured data like a phone book or configuration settings.
While both use curly braces {}, their contents differ: sets contain only values, dictionaries contain pairs separated by colons. Also, sets support operations like union and intersection, which dictionaries do not.
Code Comparison
Here is how you create and use a set to store unique numbers and check membership.
numbers = {1, 2, 3, 4, 4, 5}
print(numbers) # duplicates removed
print(3 in numbers) # check if 3 is in the set
numbers.add(6)
print(numbers)Dictionary Equivalent
Here is how you create and use a dictionary to map names to ages and access values by keys.
ages = {'Alice': 25, 'Bob': 30, 'Charlie': 35}
print(ages)
print(ages['Bob']) # access Bob's age
ages['Diana'] = 40
print(ages)When to Use Which
Choose a set when you need to store unique items and perform operations like checking membership, unions, or intersections. Sets are perfect for removing duplicates or testing if an item exists quickly.
Choose a dictionary when you need to associate values with unique keys and retrieve data by those keys. Dictionaries are best for structured data where each key maps to a specific value, like storing user information or configuration settings.