0

I have a list of lists: myList = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]] Would like to return a dictionary with key, value pairs dict={make:'Ford',model:'Mustang',......}

d ={}
for row in myList:
  for col in row:
    d[col]=row[1]

This returns the first key value pair correct {'make':'Ford','Ford':'Ford','model':'Mustang','Mustang':'Mustang'...} but then it repeats the second value.

magicsword
  • 1,179
  • 3
  • 16
  • 26
  • Possible duplicate of [Convert a list to a dictionary in Python](https://stackoverflow.com/questions/4576115/convert-a-list-to-a-dictionary-in-python) – Van Peer Nov 12 '17 at 00:44

3 Answers3

1

Just use the built-in dict funtion

myList = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]]
d = dict(myList)
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
1
d={}
for row in myList:
    d[row[0]] = row[1]

This is how you’d do this if you want to use loops, but you can also just d = dict(myList) to cast the list to a dict.

0

You can try this:

myList = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]]
final_dict = {a:b for a, b in myList}

Output:

{'make': 'Ford', 'model': 'Mustang', 'year': 1964}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102