+

Python | Convert dictionary to list of tuples

Examples :

  Input:  {`Geeks`: 10,` for`: 12, `Geek`: 31}  Output:  [(`Geeks`, 10), (` for`, 12), (`Geek`, 31)]  Input:  {` dict`: 11, `to` : 22, `list_of_tup`: 33}  Output:  [(` dict`, 11), (`to`, 22), (` list_of_tup`, 33)] 

The following are various methods for converting a dictionary to a list of tuples.

Method # 1: Using List Comprehension

# Python code to convert a dictionary to a list of tuples

 
# Dictionary initialization

dict = { `Geeks` : 10 , `for` : 12 , `Geek` : 31 }

  
# Convert to a list of tuples

list = [(k, v) for k, v in dict . items ()]

 
# Print a list of tuples

print ( list )

Exit :

 [(`Geek`, 31), (` for`, 12), (`Geeks`, 10)] 

 Method # 2: Using items()

# Python code to convert a dictionary to a list of tuples

 
# Initializing the dictionary

dict = { `Geeks` : 10 , `for` : 12 , `Geek` : 31 }

 
# Convert to list of tuples

list = list ( dict . items ())

 
# Print a list of tuples

print ( list )

Output:

 [(`for`, 12), (` Geeks`, 10), (`Geek`, 31)] 

Method # 3: Using zip

# Python code to convert a dictionary to a list of tuples

 
# Initializing the dictionary

dict = { `G eeks` : 10 , ` for` : 12 , `Geek` : 31 }

 
# Using zip

listt = zip ( dict . keys (), dict .values ​​())

  
# Convert from zip to list of objects

listt = list (listt)

< p>  
# Print list

print (listt)

Exit :

 [(`Geek`, 31), (` Geeks`, 10), (`for`, 12)] 

Method # 4 : Using iteration

# Python code to convert a dictionary to a list of tuples

  
# Initializing the dictionary

dict = { `Geeks` : 10 , `for` : 12 , ` Geek` : 31 }

 
# Initializing an empty list

list = []

 
# Iteration

for i in dict :

k = (i, dict [i])

list . append (k)

  
# Print list a

print ( list )

Output:

 [(`Geeks`, 10), (` for`, 12), (`Geek`, 31)] 

Method # 5: Using collection

# Python code to convert a dictionary to a list of tuples

 
# Initializing the dictionary

dict = { `Geeks` : 10 , `for` : 12 , ` Geek`  : 31 }

 
# Import

import collections

 
# Conversion

list_of_tuple = collections.namedtuple ( `List` , ` name value` )

  

lists = list (list_of_tuple ( * item) for item in dict . items ())

  
# Print list

print (lists)

Exit:

[List (name = `for`, value = 12), List (name = `Geek`, value = 31), List (name = `Geeks`, value = 10)]

Get Solution for free from DataCamp guru