-3

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?

Kawaiii
  • 13
  • 3

3 Answers3

0
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.

GaryMBloom
  • 5,350
  • 1
  • 24
  • 32
  • As a side note, some of the other answers talk about "dictionary comprehensions." These comprehensions (available for dicts, lists, tuples) are much more "Pythonic" than my answer. But they are not the best solution for a new programmer like the OP. A new programmer should understand the basic logic of my solution in its longer form before exploring the comprehensions. You should walk before you run. :) – GaryMBloom Nov 27 '22 at 01:34
  • Accordingly, I would add that @mkrieger1 believes that this OP's question is a duplicate of the question he refers to above, and I agree. But I would also mention that all the answers to that other question are also based on dict comprehensions, which I don't think are the right approach for newer programmers. – GaryMBloom Nov 27 '22 at 01:53
-2

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']}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
-2

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 :)