Python: Convert Tuples to Dictionaries

Dictionaries in Python are an implementation of hash tables: a data structure on which data is labeled by a key-value. This data structure is efficient for looking up data by its key, with an expected O(1) lookup time.

It is important to keep in mind that dict objects are mutable, and that the key values must be of a hashable (i.e. immutable) type.

Convert List of Tuples to a Dictionary in Python

One of the ways of creating a dictionary in Python is using a list of tuples in the (key,value) format, simply by calling the dict() method on your list:

my_data = [('John', 1), ('Joe', 2), ('Alice',3), ('Bob',4)]
my_dict = dict(my_data)
{'John': 1, 'Joe': 2, 'Alice': 3, 'Bob': 4}

In effect, this is the reverse of the dict.items() method. This is a versatile way of creating dicts! For example, you can transform your data with map before calling the dict() method:

my_data = [('John', 1), ('Joe', 2), ('Alice',3), ('Bob',4)]
my_dict = dict(map(reversed, my_data))
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

{1: 'John', 2: 'Joe', 3: 'Alice', 4: 'Bob'}

Tuples With Complex Types to Dictionary

Sometimes, depending on your application, you might want to create a dictionary with some complex key - for example, suppose that your key is composed of two values. The list type is mutable, which means it is not hashable. Therefore, the following code throws an error:

my_data = [([1,2] ,'John'), ([2,3], 'Joe'), ([3,4], 'Alice'), ([4,5],'Bob')]
my_dict = dict(my_data)
TypeError: unhashable type: 'list'

In this case, the tuple type can help us again - as tuples are immutable, they are hashable. This means we can use them as keys for our dict, as follows:

my_data = [((1,2) ,'John'), ((2,3), 'Joe'), ((3,4), 'Alice'), ((4,5),'Bob')]
my_dict = dict(my_data)
{(1, 2): 'John', (2, 3): 'Joe', (3, 4): 'Alice', (4, 5): 'Bob'}
Last Updated: April 19th, 2023
Was this helpful?

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup

Ā© 2013-2024 Stack Abuse. All rights reserved.