Python Dictionary of sets [6 Methods to create]

In this Python tutorial, I will guide you through what a Python dictionary of sets is, why it might be useful for us, and how to create a Python dict of sets using different methods present in Python.

In Python, a dictionary is a mutable and unordered collection of items, while a set is an unordered collection of unique items. Both dictionaries and sets are versatile data structures in Python that offer a variety of use cases. Combining them, we can create a Python dictionary of sets.

What is a Python Dictionary of Sets?

A dictionary in Python is a collection of key-value pairs where each key must be unique. On the other hand, a set in Python is an unordered collection of unique elements. When we talk about a Python dictionary of sets, we refer to a dictionary in Python where each key maps to a set.

Examples: Let’s create a Python dictionary of sets that represents some of the most populous cities in California and Florida.

USA = {
    'California': {'Los Angeles', 'San Francisco', 'San Diego'},
    'Florida': {'Miami', 'Orlando', 'Tampa'}

Output: In this above Python code, I have a dictionary named ‘USA‘, which have ‘California‘ and ‘Florida‘ as keys and some names of popular cities as a Python set as their respective values. I have used type() function in Python, that confirms the thing I have created is a Python dictionary.

set dictionary python

Why to Use a Dictionary of Sets Python?

  • Unique Values: One of the prime uses of sets in Python is to maintain unique values. In the context of a Python dictionary, this means ensuring that each key has a collection of unique values.
  • Fast Membership Testing: Sets offer O(1) average time complexity for checking the existence of an element.
  • Flexibility: Python Dictionary of sets provides a structured way to manage categories of unique items.
READ:  6 Ways to Save image to file in Python

Creating Dictionary of Sets in Python

There are many different methods present in Python to create a Python dictionary of sets:

  • Using {} (Curly Braces)
  • Using dict()
  • Dictionary Comprehension
  • Using defaultdict
  • Using setdefault
  • Using a For Loop

Lets see them one by one using some illustrative examples:

Method 1: Dictionary of Sets Python using {}

This is the most straightforward way to create a dictionary. By enclosing key-value pairs within curly braces {}, you can define and initialize a Python dictionary.

Scenario: Let’s consider a situation where we have to directly list the most populated city in each state using Python dictionary of sets, so that no repeated cities are stored in our data.

most_populated_city = {
    'California': {'Los Angeles'},
    'New York': {'New York City'},
    'Texas': {'Houston'}

Output: In this scenario, we’ve directly created a Python dictionary with states as keys and sets containing their most populated cities as values using {}.

{'California': {'Los Angeles'}, 'New York': {'New York City'}, 'Texas': {'Houston'}}
<class 'dict'>
dictionary of sets in Python.

This way we easily initialize a Python dictionary of sets using curly braces{}.

Method 2: Set Dictionary in Python using dict()

The dict() constructor can be used to create a Python dictionary. To create a dictionary of sets, the value for each key in the constructor should be a set.

Scenario: Let’s Create a Python dictionary to showcase the capital cities of selected states.

capitals = dict(

Output: Here, we’re using the dict() function to build a Python dictionary where each state (key) is associated with a set containing its capital city.

{'California': {'Sacramento'}, 'Texas': {'Austin'}, 'Florida': {'Tallahassee'}}
<class 'dict'>
python dictionary of sets

This way we can use the dict() function in Python to create dictionary of sets.

Method 3: Python Dictionary Set Value using Dictionary Comprehension

Python supports a compact way to create dictionaries using comprehensions. Dictionary comprehensions provide a concise way to generate dictionaries from iterables like set in Python. We can nest a set comprehension within a dictionary comprehension to create a Python dictionary of sets.

Example: Consider a situation where we as a Python developer got a work to categorize cities by the initial letter of their names.

cities = ['Austin', 'Albany', 'Anaheim', 'Boston', 'Buffalo', 'Baltimore']
cities_by_initial = {char: {city for city in cities if city.startswith(char)} for char in 'AB'}

Output: Here, we’re iterating over a list in Python of cities and grouping them by their initial letters using dictionary and set comprehensions.

{'A': {'Austin', 'Anaheim', 'Albany'}, 'B': {'Boston', 'Baltimore', 'Buffalo'}}
<class 'dict'>
python dict of sets

This way we can use dictionary and set comprehension to create Python dictionary of sets.

READ:  How to Convert a Dictionary to a String in Python? [3 useful methods]

Method 4: Python Set Dict Value using defaultdict()

The collections module provides defaultdict which is a subclass of the built-in dict class in Python. It allows specifying a default value type for the dictionary in Python, which in our case would be a set, which will be used if a key doesn’t already exist in the Python dictionary.

Scenario: Let’s create a Python dict of sets which catalogue popular tourist attractions by state in USA.

from collections import defaultdict

attractions = [('California', 'Golden Gate Bridge'), ('New York', 'Statue of Liberty'), ('California', 'Hollywood Sign')]
attractions_by_state = defaultdict(set)
for state, attraction in attractions:


Output: With defaultdict(set), if a state doesn’t exist as a key, it’s automatically associated with an empty set in Python. This makes the process of adding attractions more straightforward.

defaultdict(<class 'set'>, {'California': {'Hollywood Sign', 'Golden Gate Bridge'}, 'New York': {'Statue of Liberty'}})
<class 'collections.defaultdict'>
set of dictionaries python

This way we can use the defaultdict from collections module in dict class to create a Python dictionary of sets.

Method 5: Python Dict Set Value using setdefault method

The setdefault method of dictionaries returns the value of the specified key if it exists. If not, it inserts the key with the specified value. This is useful for creating a Python dictionary of sets as it can help ensure that each key maps to a set.

Scenario: Consider a situation where we as a Python developer got a work to Track major airports in various states.

airports = [('Texas', 'Dallas/Fort Worth International Airport'), ('California', 'Los Angeles International Airport'), ('Texas', 'George Bush Intercontinental Airport')]
airports_by_state = {}
for state, airport in airports:
    airports_by_state.setdefault(state, set()).add(airport)


Output: The setdefault method of dictionaries in Python allows you to fetch the value of a given key if it exists. If not, it sets a default value for that key. So here, for each state, we’re using setdefault to either get the existing set of airports or establish a new empty set in Python, to which we then add the airport.

{'Texas': {'George Bush Intercontinental Airport', 'Dallas/Fort Worth International Airport'}, 'California': {'Los Angeles International Airport'}}
<class 'dict'>
python set dictionary value

This way we can use the setdefault method to create a Python dictionary of sets.

READ:  Python write array to CSV [4 Methods]

Method 6: Python Dictionary set using for loop

A simple for loop can iterate over data and populate a dictionary of sets. This is a more manual approach compared to the others.

In this approach, for each (key, value) pair in the data list in Python, we first check if the key exists in the Python dictionary. If it doesn’t, we initialize it with an empty set in Python. Then, we add the value to the set corresponding to the key.

Example: Let’s map some states to their known universities with the help of some methods in Python.

universities = [('Massachusetts', 'Harvard'), ('California', 'Stanford'), ('Massachusetts', 'MIT')]
universities_by_state = {}
for state, university in universities:
    if state not in universities_by_state:
        universities_by_state[state] = set()

Output: In this example, we’re manually checking if a state exists in the dictionary. If not, we create an entry with an empty set and then add the university to the set.

{'Massachusetts': {'Harvard', 'MIT'}, 'California': {'Stanford'}}
<class 'dict'>
dictionary set in Python

This way we can use for loop with if conditional statement to create a Python dictionary of sets.


Understanding what the Python dictionary of sets is, why it is useful and how to create one Python dictionary of sets using different methods like curly braces{}, dict() function, dictionary with set comprehension, defaultdict(), setdefault, and for loop with conditional statements.

Additionally, we have also seen some illustrative examples related to all methods mentioned above, that how one can use these methods to create a dictionary of sets in Python.

This is now totally upto the developer choice, which method to select for their problems.

You may also like to read our different Python articles: