w3resource

Python: Convert a given list of lists to a dictionary

Python dictionary: Exercise-63 with Solution

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

Sample Solution:

Python Code:

def test(lst):
    result = {item[0]: item[1:] for item in lst}
    return result

students = [[1, 'Jean Castro', 'V'], [2, 'Lula Powell', 'V'], [3, 'Brian Howell', 'VI'], [4, 'Lynne Foster', 'VI'], [5, 'Zachary Simon', 'VII']]

print("\nOriginal list of lists:")
print(students)
print("\nConvert the said list of lists to a dictionary:")
print(test(students))

Sample Output:

Original list of lists:
[[1, 'Jean Castro', 'V'], [2, 'Lula Powell', 'V'], [3, 'Brian Howell', 'VI'], [4, 'Lynne Foster', 'VI'], [5, 'Zachary Simon', 'VII']]

Convert the said list of lists to a dictionary:
{1: ['Jean Castro', 'V'], 2: ['Lula Powell', 'V'], 3: ['Brian Howell', 'VI'], 4: ['Lynne Foster', 'VI'], 5: ['Zachary Simon', 'VII']}

Pictorial Presentation:

Python Dictionary: Convert a given list of lists to a dictionary.

Flowchart:

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

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to extract values from a given dictionaries and create a list of lists from those values.
Next: Write a Python program to create a key-value list pairings in a given dictionary.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Free up Memory:

  • Manual garbage collection can be performed on timely or event based mechanism.
import gc
collected_objects = gc.collect()