Convert Lists and Dictionaries to Sets in Python

Convert lists of pairs into dictionaries and lists or dictionaries into sets using simple helper functions.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 14 views 0 copies

Python code

41 lines
Python 3.9+
def convert_to_dict(data):
    """Convert list of tuples or lists into a dictionary."""
    return dict(data)


def convert_to_set(data):
    """Convert list or dictionary into a set of its keys/values."""
    if isinstance(data, dict):
        return set(data.keys())
    return set(data)


def convert_collection(data, target):
    """Convert data to dictionary or set based on target parameter."""
    if target == "dict":
        return convert_to_dict(data)
    elif target == "set":
        return convert_to_set(data)
    else:
        raise ValueError("Target must be 'dict' or 'set'")


if __name__ == "__main__":
    pairs = [("name", "Alice"), ("age", 30), ("city", "Paris")]
    numbers = [3, 1, 4, 1, 5, 9, 2, 6]

    print("Original pairs:", pairs)
    print("As dictionary:", convert_to_dict(pairs))
    print()
    print("Original numbers:", numbers)
    print("As set:", convert_to_set(numbers))

    sample_dict = {"a": 1, "b": 2, "c": 3}
    print()
    print("Original dict:", sample_dict)
    print("Keys as set:", convert_to_set(sample_dict))

    test_data = [("x", 10), ("y", 20)]
    print()
    print("Convert to dict:", convert_collection(test_data, "dict"))
    print("Convert to set:", convert_collection([1, 2, 2, 3], "set"))

Output

stdout
Original pairs: [('name', 'Alice'), ('age', 30), ('city', 'Paris')]
As dictionary: {'name': 'Alice', 'age': 30, 'city': 'Paris'}

Original numbers: [3, 1, 4, 1, 5, 9, 2, 6]
As set: {1, 2, 3, 4, 5, 6, 9}

Original dict: {'a': 1, 'b': 2, 'c': 3}
Keys as set: {'a', 'b', 'c'}

Convert to dict: {'x': 10, 'y': 20}
Convert to set: {1, 2, 3}

How it works

The dict() constructor converts a list of key-value pairs (tuples or lists) into a dictionary, mapping the first element of each pair to the second. set() creates a set from any iterable, automatically removing duplicate elements. When given a dictionary, set() iterates over its keys, so set(some_dict) produces the keys; the isinstance check makes this explicit and readable. The convert_collection function branches on the target string to expose the correct behavior while raising a clear ValueError for unsupported targets. These helpers abstract away the built-in syntax so callers can write semantic conversion code.

Common mistakes

  • Passing a dictionary directly to `set()` expecting values; it yields keys only.
  • Forgetting that `dict()` requires an iterable of 2-item pairs or a mapping.
  • Returning a new set/dict instead of modifying in place when that's the intent.
  • Not handling unsupported target values with a clear error message.

Variations

  1. Use `{k: v for k, v in pairs}` or `dict(pairs)` for more explicit control.
  2. Use `set(data.keys())` or just `set(data)` for dictionary-to-set conversion.

Real-world use cases

  • Normalizing API response key-value pairs into a dictionary before mapping to a model.
  • Deduplicating user-provided lists (IDs, emails) by converting to a set for fast lookups.
  • Checking which keys exist across multiple data records by collecting key sets per record.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.