6. Conversions between data structures

Quiz: 0/5

When working with Python, you'll often find yourself needing to switch between different data structures like lists, tuples, sets, and dictionaries. Each of these has unique properties, and converting between them can make your code more efficient or easier to work with.

Why convert between data structures?

Sometimes, a specific data structure is better suited for your task:

  • Lists are great for ordered data and when you need to change the values (mutable).
  • Tuples are useful for fixed, unchangeable (immutable) collections.
  • Sets are perfect for removing duplicates or testing membership quickly.
  • Dictionaries let you pair data using a key-value structure for fast lookups.

How to convert between data structures?

Converting to a List list()

You might want to convert to a list to make data editable or iterate through it in order:

  • From a Tuple: list((1, 2, 3))[1, 2, 3]
  • From a Set: list({1, 2, 3})[1, 2, 3]
  • From a Dictionary (keys): list({'a': 1, 'b': 2})['a', 'b']

Converting to a Tuple tuple()

Tuples are great when the order matters and the data shouldn’t change:

  • From a List: tuple([1, 2, 3])(1, 2, 3)
  • From a Set: tuple({1, 2, 3})(1, 2, 3)

Converting to a Set set()

Sets are used to remove duplicates or perform mathematical set operations:

  • From a List: set([1, 1, 2, 3]){1, 2, 3}
  • From a Tuple: set((1, 2, 2, 3)){1, 2, 3}

Converting to a Dictionary dict()

Dictionaries pair values (key-value format). You often need structured data for fast lookups:

  • From a List of Tuples: dict([('a', 1), ('b', 2)]){'a': 1, 'b': 2}
  • From Two Lists (keys and values):
    keys = ['a', 'b']
    values = [1, 2]
    dict(zip(keys, values))  # → {'a': 1, 'b': 2}
    

Use cases for each conversion

Removing duplicates

Convert a list to a set:

numbers = [1, 1, 2, 3, 3]
unique_numbers = set(numbers)  # {1, 2, 3}

Creating Dictionaries

Use a list of pairs to create a dictionary:

pairs = [('apple', 3), ('banana', 5)]
fruit_counts = dict(pairs)  # {'apple': 3, 'banana': 5}

Sorting and preserving order

Convert a set to a list if you need an ordered collection:

unique_numbers = {3, 1, 2}
sorted_list = list(sorted(unique_numbers))  # [1, 2, 3]

Making data immutable

Convert a list to a tuple to ensure it can’t be changed:

fruits = ['apple', 'banana']
immutable_fruits = tuple(fruits)  # ('apple', 'banana')

Practice example

Here’s how you might use these conversions in a real-world scenario:

Task: Remove duplicates from a list and pair each item with its length

fruits = ['apple', 'banana', 'apple', 'cherry']
# Remove duplicates by converting to a set
unique_fruits = set(fruits)  # {'apple', 'banana', 'cherry'}

# Create a dictionary of fruit names and their lengths
fruit_lengths = {fruit: len(fruit) for fruit in unique_fruits}
print(fruit_lengths)  # {'apple': 5, 'banana': 6, 'cherry': 6}

Summary table

Conversion Syntax Example
List to Tuple tuple(list_data) tuple([1, 2, 3])(1, 2, 3)
List to Set set(list_data) set([1, 1, 2]){1, 2}
List to Dictionary dict(zip(keys, values)) dict(zip(['a', 'b'], [1, 2])){'a': 1, 'b': 2}
Set to List list(set_data) list({1, 2, 3})[1, 2, 3]
Tuple to List list(tuple_data) list((1, 2, 3))[1, 2, 3]
List of Tuples to Dict dict(list_of_tuples) dict([('a', 1), ('b', 2)]){'a': 1, 'b': 2}

 

By practicing these conversions, you'll become more confident in choosing the right data structure for your task!

Hands-On Practise

Exercise: Data cleanup and transformation

You have the following data:

data = [
    ('Alice', 25), 
    ('Bob', 30), 
    ('Alice', 25), 
    ('Charlie', 35), 
    ('Bob', 30), 
    ('Diana', 40)
]

Your Tasks:

  1. Remove duplicates

    • Convert the data into a format where duplicates are eliminated.
  2. Convert to a Dictionary

    • Use the cleaned data to create a dictionary where:
      • The name is the key.
      • The age is the value.
  3. Extract and sort Names

    • Convert the dictionary keys (names) into a list.
    • Sort the list alphabetically.
  4. Convert to immutable format

    • Convert the sorted list of names into a tuple to ensure it cannot be changed.
  5. Summary of ages

    • Use the dictionary to extract all unique ages into a set.
Output:
Loading...

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonSets in PythonNext lessonPython Modules and Libraries