w3resource

Python: Convert a given dictionary into a list of lists

Python dictionary: Exercise-56 with Solution

Write a Python program to convert a dictionary into a list of lists.

Sample Solution:

Python Code:

# Define a function 'test' that converts a dictionary into a list of lists containing key-value pairs.
def test(dictt):
    # Use the 'items' method to get key-value pairs, then convert it to a list of lists.
    result = list(map(list, dictt.items()))
    return result    

# Create a dictionary 'color_dict' with numeric keys and corresponding color names as values.
color_dict = {1 : 'red', 2 : 'green', 3 : 'black', 4 : 'white', 5 : 'black'}

# Print a message indicating the start of the code section and the dictionary being processed.
print("\nOriginal Dictionary:")
print(color_dict)

# Call the 'test' function to convert the dictionary into a list of lists and print the result.
print("Convert the said dictionary into a list of lists:")
print(test(color_dict))

# Create another dictionary 'color_dict' with string keys and corresponding names as values.
color_dict = {'1' : 'Austin Little', '2' : 'Natasha Howard', '3' : 'Alfred Mullins', '4' : 'Jamie Rowe'}

# Print a message indicating the start of the code section and the new dictionary being processed.
print("\nOriginal Dictionary:")
print(color_dict)

# Call the 'test' function to convert the dictionary into a list of lists and print the result.
print("Convert the said dictionary into a list of lists:")
print(test(color_dict)) 

Sample Output:

Original Dictionary:
{1: 'red', 2: 'green', 3: 'black', 4: 'white', 5: 'black'}
Convert the said dictionary into a list of lists:
[[1, 'red'], [2, 'green'], [3, 'black'], [4, 'white'], [5, 'black']]

Original Dictionary:
{'1': 'Austin Little', '2': 'Natasha Howard', '3': 'Alfred Mullins', '4': 'Jamie Rowe'}
Convert the said dictionary into a list of lists:
[['1', 'Austin Little'], ['2', 'Natasha Howard'], ['3', 'Alfred Mullins'], ['4', 'Jamie Rowe']]

Flowchart:

Flowchart: Convert a given dictionary into a list of lists.

Python Code Editor:

Previous: Write a Python program to access dictionary key's element by index.
Next: Write a Python program to filter even numbers from a given dictionary values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/dictionary/python-data-type-dictionary-exercise-56.php