FireBird
FireBird

Reputation: 11

converting list into dictionary using for loop

I'm trying to convert a list -created from a dataframe- to a dictionary in python. I am fairly new to this area of python, so if I have done something wrong please point it out.

Lets suppose I have a list: a = [['Robert'], ['Tommy'], ['Joe'], ['Will']]

The key is supposed to be 'Name', and the value as the string in the list.

I have tried: dct = {'Name': a[i] for i in range(len(a))}

I would end up getting: {'Name': ['Will']} Not sure if this is necessary, but I only got the last value in the list. Please can anyone point out what is going wrong here.

Upvotes: 0

Views: 390

Answers (2)

Aman Raheja
Aman Raheja

Reputation: 615

If this can work!


dct = {}
for i in range(len(a)):
    dct['Name'] = a
print dct

Upvotes: 0

Simeon Visser
Simeon Visser

Reputation: 122436

This happens because it's repeatedly assigning a new value to the key 'Name' in that dictionary. The dictionary comprehension that you've written behaves the same as:

dct = {}
for i in range(len(a)):
    dct['Name'] = a[i]

So that's why afterwards you end up with a dictionary that has one key in it with the last value.

Upvotes: 1

Related Questions