Convert dictionary to list

Python program to convert the dictionary into list of tuples using list comprehension

Input- Dictionary: { ‘Welcome’: 35, ‘to’: 5, ‘Dataquest’: 54 }
Output- List: [ (‘Welcome’, 35), (‘to’, 5), (‘Dataquest’, 54) ]

# Python code to convert dictionary into list of tuples 
# Initialization of dictionary 
dict = { 'Welcome': 35, 'to': 5, 'Dataquest': 54 }
# Converting into list of tuple 
list = [(k, v) for k, v in dict.items()] 
# Printing list of tuple 


 [('Welcome', 35), ('Dataquest', 54), ('to', 5)]

You are iterating with the for in your statement. List comprehension is used for iteration.

1 Like

Every list comprehension in Python includes three elements:

  1. expression is the member itself, a call to a method, or any other valid expression that returns a value. In the example above, the expression i * i is the square of the member value.
  2. member is the object or value in the list or iterable. In the example above, the member value is i .
  3. iterable is a list, set, sequence, generator, or any other object that can return its elements one at a time. In the example above, the iterable is range(10) .

Apologies. My bad. I was referring to this: :sweat_smile:
We don’t need to use the following iteration method.
# Initialization of dictionary

dict = { 'Welcome' : 5 , 'to' : 17 , 'Dataquest' : 13 }

# Initialization of empty list

list = []

# Iteration

for i in dict :

k = (i, dict [i])

list .append(k)

# Printing list

print ( list )

1 Like

Thank you correcting me. I have revised the topic regarding the same.

1 Like