Reputation:
I have a list of lists: [['1','Kate','Green','North'],['2','John','Blue','North'],['3','Jane','Red','NorthSouth'],['4','Lewis','Blue','East']]
I want to make a dictionary: {'1': ['Kate','Green','North'], '2':['John','Blue','North'], '3':['Jane','Red','NorthSouth'], 4:['Lewis','Blue','East']}
Currently, my code is:
def li2dict(li):
final_dict = {}
for i in range(len(li)):
for j in range(len(li[j])):
roster_dict[li[j][0]] = li[j][k]
print(final_dict)
However, all I am getting is: {'1':'North', '2':'North', '3':'NorthSouth', '4':'East'} Can anyone help me with this logic error?
Edit 1: FYI, I am not allowed to import any libraries.
Edit 2: I have also tried:
roster_dict[contents[j][0]].append(contents[j][k])
But I get:
File "test.py", line 54, in <module>
main()
File "test.py", line 51, in main
li2dict([listinfo])
File "test.py", line 44, in li2dict
roster_dict[contents[j][0]].append(contents[j][k])
KeyError: '1'
Upvotes: 1
Views: 44
Reputation: 93
Looks like your question was already answered, but here is another answer that is more similar to your format which may help you better understand the logic
old_list = [['1','Kate','Green','North'],['2','John','Blue','North'],['3','Jane','Red','NorthSouth'],['4','Lewis','Blue','East']]
def dict_conversion(list_variable):
dict = {}
for list in list_variable:
index_position = list[0]
list_content = list[1:]
dict[index_position] = list_content
print(dict)
return dict
dict_conversion(old_list)
Upvotes: 2
Reputation: 715
Try using dict comprehension:
d = {i[0]: i[1:] for i in li}
print(d)
{'1': ['Kate', 'Green', 'North'], '2': ['John', 'Blue', 'North'], '3': ['Jane', 'Red', 'NorthSouth'], '4': ['Lewis', 'Blue', 'East']}
Upvotes: 1