How to turn this list of lists into a dictionary where the first item of each sublist is used as key?

Question:

The original list is:
[['James', '100.00', '90.00', '85.50'], ['Nick', '78.00', '85.00', '80.50'], ['William', '95.50', '92.00', '100.00']]

I want to turn the list into a dictionary that look like this:
{'James': ['100.00', '90.00', '85.50'], 'Nick': ['78.00', '85.00', '80.50'], 'William': ['95.50', '92.00', '100.00']}

Could anyone please tell me how to get the output for this?

Asked By: Kawaiii

||

Answers:

We can use a dictionary comprehension:

inp = [['James', '100.00', '90.00', '85.50'], ['Nick', '78.00', '85.00', '80.50'], ['William', '95.50', '92.00', '100.00']]
d = {x[0]: x[1:4] for x in inp}
print(d)

This prints:

{'James': ['100.00', '90.00', '85.50'],
 'Nick': ['78.00', '85.00', '80.50'],
 'William': ['95.50', '92.00', '100.00']}
Answered By: Tim Biegeleisen
d = {}
for sublist in orig_list:
    new_key, new_value = sublist[0], sublist[1:]
    d[new_key] = new_value

Since you’re a beginner, it’s best to take a beginner’s approach…

You want a dictionary, so you start by creating an empty one.
Then we’ll iterate over the list you’ve been given, and for each sublist of the list, we’ll take the first element and make it a new key in the dictionary. And we’ll take the remaining elements of the list and make them a new value of the new key.

When you’re done processing, you’ll have the dict that you want.

Since others mention a "dictionary comprehension," I’ll add that to my answer, as well. A dict comp. that corresponds to what I’ve done above could be:

d = {sublist[0]: sublist[1:] for sublist in orig_list}

But, as I’ve mentioned below in my comments, I don’t think a dictionary comprehension is appropriate for a beginner programmer. My first solution is the better one.

Answered By: GaryMBloom

you can turn it into a dictionary using the following code:

lst = [
    ["James", "100.00", "90.00", "85.50"],
    ["Nick", "78.00", "85.00", "80.50"],
    ["William", "95.50", "92.00", "100.00"],
]

new_dict = {}
for person in lst:
    new_dict[person[0]] = person[1:]

print(lst) # original lst
print(new_dict) # new dictionary

The final output will be like this:

{'James': ['100.00', '90.00', '85.50'], 'Nick': ['78.00', '85.00', '80.50'], 'William': ['95.50', '92.00', '100.00']}

Hope this help 🙂

Answered By: CathyL

Maybe you can try this following code :

list1 = [
    ['James', '100.00', '90.00', '85.50'],
    ['Nick', '78.00', '85.00', '80.50'],
    ['William', '95.50', '92.00', '100.00']
]

list1_to_dict = dict((x[0], x[1:]) for x in list1)
print(list1_to_dict)

Hope it will help you 🙂

Answered By: hafshahfitri
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.