Converting Tuples to Lists, Sets, and Dictionaries in Python. | 1
|

Converting Tuples to Lists, Sets, and Dictionaries in Python.

Tuples are one of the four types of collections in Python. Lists, Sets, and Dictionaries are the other three.

Tuples have a slight advantage over lists when it comes to performance. But at the expense of some flexibility. Unlike lists, tuples don’t allow modifications.

Sets are another similar collection type to tuples. Yet, sets don’t allow duplicates, and they are not ordered. In contrast, lists and tuples are ordered and allow repeated elements. Thus, sets are not indexed, and they don’t support slicing operations as lists and tuples do.

Dictionaries are a type of key-value mapping in Python. Starting from Python 3.7, elements in a dictionary (key-value pairs) are ordered. You can modify dictionaries (mutable), Add or remove new items to them, or can nest them with other dictionaries.

For the many benefits of each collection type, you may want to jump from one type to the other frequently.

This post is all about how to convert tuples to other collection types.

Tuples to Lists

Lists and tuples are the most alike among all the collection types. Hence, you’d frequently encounter switching between them.

Also, these conversions are fairly easy in Python.

Converting a tuple to a list.

marvel_heros = ("Spider Man", "Captain America", "Iron Man")

# Convert the tuple to a list
marvel_heros_list = list(marvel_heros)

print(type(marvel_heros))
print(type(marvel_heros_list))

>>> <class 'tuple'>
>>> <class 'list'>

Converting a list to a tuple

marvel_heros_tuple = tuple(marvel_heros_list)
print(type(marvel_heros_tuple))

>>> <class 'tuple'>

Converting nested tuples to nested lists

Things can get slightly complicated when the tuples are nested.

If the nested tuple is strictly a tuple of tuples, you can either use a map function or list comprehension. That is, if all the tuple elements are other tuples, these functions can produce a list of lists.

harry_potter_house_charactors = (
    ("Harry Potter", "Hermione Granger", "Ron Weasley"),
    ("Severus Snape", "Draco Malfoy", "Lord Voldemort"),
    ("Luna Lovegood", "Quirinus Quirrell", "Cho Chang"),
    ("Hannah Abbott", "Fat Friar Ghost", "Teddy Lupin"),
)

print([list(house) for house in harry_potter_houses])

# OR

print(list(map(list, harry_potter_house_charactors)))

>>> [['Harry Potter', 'Hermione Granger', 'Ron Weasley'], ['Severus Snape', 'Draco Malfoy', 'Lord Voldemort'], ['Luna Lovegood', 'Quirinus Quirrell', 'Cho Chang'], ['Hannah Abbott', 'Fat Friar Ghost', 'Teddy Lupin']]

Yet, if your outer tuple has other data types and tuples, it can be tricky.

For deeply nested tuples that also contain other types of data, the best way to convert them into a nested list is using a recursive function.

def listify(t):
    return list(map(listify, t)) if isinstance(t, (list, tuple)) else t

    harry_potter_houses = (
    (
        "Griffindor",
        ("Harry Potter", "Hermione Granger", "Ron Weasley"),
        "Minerva McGonagall",
        "Nearly Headless Nick",
    ),
    (
        "Slytherin",
        ("Severus Snape", "Draco Malfoy", "Lord Voldemort"),
        "Horace Slughorn",
        "Bloody Baron",
    ),
    (
        "Ravenclaw",
        ("Luna Lovegood", "Quirinus Quirrell", "Cho Chang"),
        "Filius Flitwick",
        "Grey Lady",
    ),
    (
        "Hufflepuff",
        ("Hannah Abbott", "Fat Friar Ghost", "Teddy Lupin"),
        "Hufflepuff",
        "Fat Friar",
    ),
)

print(listify(harry_potter_houses))

>>> [['Griffindor', ['Harry Potter', 'Hermione Granger', 'Ron Weasley'], 'Minerva McGonagall', 'Nearly Headless Nick'], ['Slytherin', ['Severus Snape', 'Draco Malfoy', 'Lord Voldemort'], 'Horace Slughorn', 'Bloody Baron'], ['Ravenclaw', ['Luna Lovegood', 'Quirinus Quirrell', 'Cho Chang'], 'Filius Flitwick', 'Grey Lady'], ['Hufflepuff', ['Hannah Abbott', 'Fat Friar Ghost', 'Teddy Lupin'], 'Hufflepuff', 'Fat Friar']]

Converting tuples to set

Like we used the list function to convert a tuple to a list, and we can also use the set function to convert a tuple to a set.

Yet, there are a few things to keep in mind when converting tuples to sets.

Sets can have only distinct, hashable values. In Python, only immutable objects, such as tuples, are hashable.

The sets themselves are non-hashable. Hence, there’s no such thing called nested sets in Python. Sets can’t have lists in them either, as lists are non-hashable as well.

Thus, as long as your tuple has only hashable elements and no duplicates, you can convert them to sets.

dc_heros = ("Superman", "Batman", "Wonder Woman")

# Convert dc_heros to a set
dc_heros_set = set(dc_heros)

print(dc_heros_set)
{'Superman', 'Batman', 'Wonder Woman'}

If you still want to have a set of sets, you can use Frozenset. It’s an alternate implementation of sets in Python. Unlike sets, frozen sets are hashable.

set([['hello']])
>>> Traceback (most recent call last):
>>>  File "<stdin>", line 1, in <module>
>>> TypeError: unhashable type: 'list'


frozenset([('hello')])
>>> frozenset({'hello'})

Converting a set to a tuple is also straightforward. We only have to use the tuple constructor.

tuple({'Superman', 'Batman', 'Wonder Woman'})
>>> ('Batman', 'Superman', 'Wonder Woman')

Tuples to dictionaries.

Lists, sets, and tuples are array-like objects. Converting them to another one has no issues. But dictionaries are key-value pairs.

Converting a single tuple to a dict.

Since dictionaries are key-value pairs, we need to pair each element of a tuple with another value. The easiest way to do this is to use the enumerate function.

dict(enumerate(('Batman', 'Superman', 'Wonder Woman')))
>>> {0: 'Batman', 1: 'Superman', 2: 'Wonder Woman'}

We can now access the dictionary elements by their indexes. This is because enumerate pairs each element with it’s index in the array.

Converting 2-tuples to a dictionary

2-tuples are nested tuples where each element of the outer tuple is also a tuple with strictly two items. As long as the first element is a hashable type, the dict constructor will convert it to a dictionary. Each tuple will become a key-value pair in the resulting dictionary. The second element has no restriction in terms of hashability.

dict(
...     (
...         ("house", "Griffindor"),
...         ("head", "Minerva McGonagall"),
...         ("ghost", "Nearly Headless Nick"),
...         ("members", ["Harry Potter", "Hermione Granger", "Ron Weasley"]),
...     )
... )
>>> {'house': 'Griffindor', 'head': 'Minerva McGonagall', 'ghost': 'Nearly Headless Nick', 'members': ['Harry Potter', 'Hermione Granger', 'Ron Weasley']}


dict(
...     (
...         ("house", "Griffindor"),
...         ("head", "Minerva McGonagall"),
...         ("ghost", "Nearly Headless Nick"),
...         (["members"], ["Harry Potter", "Hermione Granger", "Ron Weasley"]),
...     )
... )
>>> Traceback (most recent call last):
>>>   File "<stdin>", line 1, in <module>
>>> TypeError: unhashable type: 'list'

Converting two tuples/lists (keys, and values) to a dictionary

Often we’ll have a list of keys and a list of values. We need to pair them elementwise and create a dictionary.

We can use the zip function to pair two lists together.

keys = ["house", "members", "head", "ghost"]

values = [
    "Slytherin",
    ("Severus Snape", "Draco Malfoy", "Lord Voldemort"),
    "Horace Slughorn",
    "Bloody Baron",
]

dict(zip(keys, values))

>>> {'house': 'Slytherin', 'members': ('Severus Snape', 'Draco Malfoy', 'Lord Voldemort'), 'head': 'Horace Slughorn', 'ghost': 'Bloody Baron'}

The two lists can be any lists, tuples, or sets. But, the keys list should always contain hashable elements, whereas the values list can have any.

Final thoughts

This post covered a critical aspect of tuples. It discusses how to convert tuples to other iterable types and create tuples from them.

Tuples are ordered, indexed array-like, immutable objects. Converting them to lists will usually have no problems as lists are more flexible.

Yet, sets and dictionaries have more rules than tuples.

Hence, when converting tuples to sets, we need to ensure that the elements are hashable and are not repeated.

Also, when converting them to dictionaries, we should first create pairs or have 2-tuples. If not, we must use enumerate or zip to create pairs. Also, we should ensure the key elements in the resulting dictionaries are always hashable.

Related: How to Execute Shell Commands With Python?

Similar Posts