Converting list of dictionaries to a set


This Python code creates a set named dict_set by converting a list of dictionaries, list_of_dicts, into frozensets of key-value pairs. Here's how the code works:

  • list_of_dicts = [{"a": 1, "b": 2}, {"b": 2, "c": 3}, {"c": 3, "d": 4}]: This line initializes a list of dictionaries named list_of_dicts. Each dictionary contains key-value pairs.
  • dict_set = {frozenset(d.items()) for d in list_of_dicts}: This line uses a set comprehension to create the dict_set set. For each dictionary d in list_of_dicts, it converts the key-value pairs into a frozenset using frozenset(d.items()).
    • for d in list_of_dicts: This part of the code iterates through each dictionary in the list_of_dicts.
    • frozenset(d.items()): It converts the key-value pairs of the dictionary into a frozenset. A frozenset is used because it is an immutable type and can be included in a set.
  • print(list_of_dicts): This line prints the original list_of_dicts to the console.
  • print(dict_set): This line prints the dict_set set (which contains frozensets of key-value pairs from the original dictionaries) to the console.

Source Code

list_of_dicts = [{"a": 1, "b": 2}, {"b": 2, "c": 3}, {"c": 3, "d": 4}]
dict_set = {frozenset(d.items()) for d in list_of_dicts}
print(list_of_dicts)
print(dict_set)

Output

[{'a': 1, 'b': 2}, {'b': 2, 'c': 3}, {'c': 3, 'd': 4}]
{frozenset({('a', 1), ('b', 2)}), frozenset({('d', 4), ('c', 3)}), frozenset({('b', 2), ('c', 3)})}

Example Programs