user3591798
user3591798

Reputation: 1

Converting a list to a dictionary troubles

I am reading lines from a file and appending each line to a list. This is fine, however I am having trouble going from ['A','B', 'C', 'D', ... 'last element'], ['A','B','C','D', ...'last element'], .... to {'A':['B','C','D', ... 'last element'], ....} I can separate the key I want in each line, but when I try to convert it to a dictionary it goes {'A':['last element'], ...}

ct = 0
myKey = eachList[0]

for el in eachList:
    subList = []
    if ct != 0:
        subList.append(eachList[ct])
        myDict[myKey] = subList
    ct+=1

I searched the forum, but the topics were either using ittertools/ izip or I just couldn't follow. Any help is appreciated!

Upvotes: 0

Views: 73

Answers (1)

oz123
oz123

Reputation: 28858

Here is a snippet of code, how you can simply read lines into a dictionary:

final_dict = {}

with open('text.txt') as f:
    for line in f.readlines():
        raw = line.strip().split(',')
        final_dict[raw[0]] = raw[1:]

Given the following input:

k1, v11, v12, v13
k2, v21, v22, v23
k3, v31, v32, v33

final_dict will be:

 {'k3': [' v31', ' v32', ' v33'], 'k2': [' v21', ' v22', ' v23'], 'k1': [' v11', ' v12', ' v13']}

Upvotes: 1

Related Questions