首页 > 解决方案 > Print out dictionary from file

问题描述

E;Z;X;Y

I tried

    dl= defaultdict(list)
    for line in file:
        line = line.strip().split(';')
        for x in line:
            dl[line[0]].append(line[1:4])
    dl=dict(dl)

    print (votep)

It print out too many results. I have an init that reads the file.

What ways can I edit to make it work?

标签: pythonfiledictionary

解决方案


The csv module could be really handy here, just use a semicolon as your delimiter and a simple dict comprehension will suffice:

with open('filename.txt') as file:
    reader = csv.reader(file, delimiter=';')
    votep = {k: vals for k, *vals in reader}
    print(votep)

Without using csv you can just use str.split:

with open('filename.txt') as file:
    votep = {k: vals for k, *vals in (s.split(';') for s in file)}
    print(votep)

Further simplified without the comprehension this would look as follows:

votep = {}
for line in file:
    key, *vals = line.split(';')
    votep[key] = vals

And FYI, key, *vals = line.strip(';') is just multiple variable assignment coupled with iterable unpacking. The star just means put whatever’s left in the iterable into vals after assigning the first value to key.


推荐阅读