Difference Between Set and Dictionary in Python - Python Tutorial | Logic Practice
Python Course / Collections / Difference Between Set and Dictionary in Python

Difference Between Set and Dictionary in Python

BLUF: This lesson on Difference Between Set and Dictionary in Python provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: Difference Between Set and Dictionary in Python

Mastering Difference Between Set and Dictionary in Python is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

In Python, the primary built-in data structures include sets and dictionaries. A set is defined as an unordered and unindexed collection that contains distinct elements. Conversely, a dictionary is an indexed collection that is also unordered, but it organizes information in pairs known as 'key-value' pairs.

Although both of these are utilized for the purpose of storing collections of data and have some common characteristics, they exhibit notable differences in their structure, functionality, and use cases.

What is a Set in Python?

In Python, a set represents one of the four fundamental data types utilized for holding collections, alongside lists, tuples, and dictionaries. It serves as an unordered aggregation of distinct elements. Sets are deemed mutable, enabling the addition or removal of items even post the creation of the set.

Sets are denoted by curly braces {}, with elements within the set being separated by commas. Typically, the set function is employed to create an empty set, while {} is reserved for initializing an empty dictionary.

Characteristics of a Set

Here are some major characteristics of Python Set:

  • Unordered: Elements in a set do not have any particular order.
  • Mutable : Elements can be added or removed from a set after its creation (e.g., with add , remove , discard ).
  • No Duplicates: Sets have unique elements; duplicates are simply ignored (if present).

Let us see an example to create sets in Python .

Python Set Example

Let us see an example to create sets in Python .

Example

Example

#creating the first set

first_set = set(("Example", 14, (1, 2, 3)))

#printing the first set

print(first_set)

#creating the second set

second_set = set("Example")

#printing the second

print(second_set)

Output:

Output

{'Example', (1, 2, 3), 14}

{'n', 't', 'i', 'T', 'o', 'c', 'p', 'e', 'h'}

What is a Dictionary in Python?

A Dictionary is a fundamental data structure available in Python that allows for the organization of data using 'key: value' pairs. Starting from Python version 3.7, dictionaries maintain the order of insertion, although they are inherently unordered collections. They are mutable and indexed, ensuring that each key is distinct and corresponds to a specific value. Dictionaries are typically utilized for storing related information, such as data linked to a particular object or entity, enabling straightforward retrieval of values based on their associated keys.

Dictionaries are commonly utilized to hold interconnected data, such as details linked to a specific object or entity, allowing for straightforward retrieval through its corresponding key.

Characteristics of a Dictionary

Python dictionary comes up with several features, which are as follows:

  • Unordered: Dictionaries do not follow a particular order to store items. However, starting from Python 3.7+, the Order is maintained when inserting key-value pairs into the dictionary.
  • Mutable: One can add, delete, or change key-value pairs after the dictionary is created.
  • Unique Keys: A dictionary's keys must be distinct (unique). If you attempt to insert a new value with a present key, the value that is present with the key will be replaced.
  • Key-Based Access: Elements are accessed by their keys, not by their indices. This feature helps in finding the items based on the key.
  • Python Dictionary Example

Let's examine an example of how to create dictionaries in Python.

Example

Example

# simple program to create a dictionary in Python

# creating a dictionary

employee_data = {

    'full_name': 'Irfan Khan',

    'employee_id': 1023,

    'department': 'IT'

}

# printing result

print("Employee Data:", employee_data)

print("Data Type:", type(employee_data))

Output:

Output

Employee Data: {'full_name': 'Irfan Khan', 'employee_id': 1023, 'department': 'IT'}

Data Type: <class 'dict'>

Key Differences between Sets and Dictionaries

The subsequent points outline the fundamental distinctions between Sets and Dictionaries in Python:

Feature Set Dictionary
Definition Set is an unordered collection of unique elements. Dictionary is an ordered collection of key-value pairs.
Representation Curly braces {} Curly braces {}, but with key-value pairs.
Ordered No Yes (since Python 3.7)
Duplicates Not Allowed (only unique elements are stored) Not Allowed (keys must be unique; values can be duplicated)
Hashing Hashable (if all elements within the set are hashable) Not directly hashable (but its keys() and items() views can behave like sets for some operations in later Python versions)
Mutable Yes (elements can be added or removed) Yes (key: value pairs can be added, removed, or values modified)
Use Case Storing unique items, membership testing, set algebra operations, and removing duplicates. Mapping keys to values, efficient lookups by key, and representing structured or labelled data.

Difference between Set and Dictionary in Python FAQs

1. What is the primary difference between a set and a dictionary?

A set is a data structure designed to hold distinct values, whereas another data structure, such as a dictionary, enables us to organize data in key: value pairs.

2. Can a set be converted to a dictionary or vice versa?

Indeed, it is feasible to convert between sets and dictionaries. Nevertheless, since these two data structures are designed for distinct functionalities, it is important to execute the conversion with caution.

Transforming a Set into a Dictionary: It is possible to convert a set into a dictionary by utilizing the dict.fromkeys method, which allows for the assignment of a default value to each element within the set.

Example

Example

s = {'a', 'b', 'c'}

d = dict.fromkeys(s, 0)

Output:

Output

{'a': 0, 'b': 0, 'c': 0}

Transforming a Dictionary into a Set: A dictionary can be converted into a set by retrieving either its keys or its values:

Example

Example

d = {'x': 1, 'y': 2}

keys_set = set(d.keys())

values_set = set(d.values())

Output:

Output

{'x', 'y'}

{1, 2}

3. What data types can be stored in sets and dictionaries?

Sets: The elements that are part of a set need to be hashable, indicating that they should be of immutable types such as int, str, float, and tuple (provided the tuple only contains immutable items). Types that are mutable, such as lists, dictionaries, or even other sets, cannot be included as elements of a set and will result in a TypeError being raised.

Dictionaries: The keys utilized in a dictionary must be hashable, adhering to the same criteria that govern the elements of a set. In contrast, the values can be of any data type, which includes mutable entities like lists, dictionaries, and sets. This characteristic allows dictionaries to be more adaptable for the storage of structured or nested information, whereas sets, while more restrictive, are fine-tuned for ensuring uniqueness and enabling rapid membership checks.

4. Are sets or dictionaries suitable for storing ordered data?

Python sets are collections that do not maintain an order, meaning that the sequence in which elements are added to a set is not retained. Consequently, sets are not ideal for the purpose of storing data that requires a specific order.

Conversely, starting with Python version 3.7, dictionaries preserve the order of insertion. This ensures that the elements will stay in the sequence in which they were inserted, rendering them ideal for the storage of ordered data.

5. How do sets and dictionaries handle duplicate data during creation or updates?

Sets: When sets are created or when elements are added to an existing set, any duplicate values are automatically eliminated.

Let us take a look at the following example:

Example

Example

# Demonstrating that sets do not allow duplicates

numbers = {10, 20, 30, 20, 10}

print("Set with duplicates removed:", numbers)

Output:

Output

Set with duplicates removed: {10, 20, 30}

Dictionaries: A dictionary does not permit duplicate keys. When a key is defined multiple times, the value that is assigned last will replace any earlier values associated with that key. This behavior is illustrated in the example below:

Example

Example

# creating a dictionary

dict_1 = {

    'name': 'John',

    'age': 21,

    'age': 25,      # repeated key

    'profession': 'SDE I'

    }

print(dict_1)

Output:

Output

{'name': 'John', 'age': 25, 'profession': 'SDE I'}

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience