Convert dictionary to list of tuples in Python


Converting from one collection type to another is very common in python. Depending the data processing needs we may have to convert the key value pairs present in a dictionary to pairs representing tuples in a list. In this article we will see the approaches to achieve this.

With in

This is a straight forward approach where we just consider the

Example

 Live Demo

Adict = {30:'Mon',11:'Tue',19:'Fri'}

# Given dictionary
print("The given dictionary: ",Adict)

# Using in
Alist = [(key, val) for key, val in Adict.items()]

# Result
print("The list of tuples: ",Alist)

Output

Running the above code gives us the following result −

The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]

With zip

The zip function combines the items passed onto it as parameters. So we take the keys and values of the dictionary as parameters to the zip function and put the result under a list function. The key value pair become tuples of the list.

Example

 Live Demo

Adict = {30:'Mon',11:'Tue',19:'Fri'}

# Given dictionary
print("The given dictionary: ",Adict)

# Using zip
Alist = list(zip(Adict.keys(), Adict.values()))

# Result
print("The list of tuples: ",Alist)

Output

Running the above code gives us the following result −

The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]

With append

In this approach we take a empty list and append evry pair of key value as tuples. A for loop is designed to convert the key value pair into tuples .

Example

 Live Demo

Adict = {30:'Mon',11:'Tue',19:'Fri'}

# Given dictionary
print("The given dictionary: ",Adict)

Alist = []

# Uisng append
for x in Adict:
k = (x, Adict[x])
Alist.append(k)

# Result
print("The list of tuples: ",Alist)

Output

Running the above code gives us the following result −

The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]

Updated on: 13-May-2020

614 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements