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.

Visual Presentation:

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

Sample Solution:

Python Code:

# Define a function 'test' that takes a list of lists 'lst' as an argument.
def test(lst):
    # Use a dictionary comprehension to convert each list in 'lst' into a dictionary,
    # where the first element is the key, and the rest of the elements are values.
    result = {item[0]: item[1:] for item in lst}
    return result

# Create a list of lists 'students' where each inner list represents student information.
students = [
    [1, 'Jean Castro', 'V'],
    [2, 'Lula Powell', 'V'],
    [3, 'Brian Howell', 'VI'],
    [4, 'Lynne Foster', 'VI'],
    [5, 'Zachary Simon', 'VII']
]

# Print a message indicating the start of the code section and display the original list of lists.
print("\nOriginal list of lists:")
print(students)

# Print a message indicating the purpose and demonstrate the 'test' function's usage to convert the list of lists to a dictionary.
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']}

Flowchart:

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

Python Code Editor:

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 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-63.php