How to make a file into a dictionary?

十年热恋 提交于 2020-04-30 06:24:55

问题


I'm having trouble trying to get my file into a dictionary with multiple values

bench,103,222,32
table,833,99,23
chair,83,22,882

My code so far is

sol={}
infile= open("furniture.dat","r")
for line in infile:
     key,value=line.split(",")

I'm trying to get the words as keys and the number as the value for the dictionary, but receiving error on the split()


回答1:


Firstly, for line in infile will read each line of the file as a string.

Secondly, you're getting an error because split(",") will separate the string into different items wherever there is a comma (","), and then return those items separately.

In your case, for the first line, it'll return "Bench" "2750" "3000" "2880", which are 4 items, while you've only written the code to store them with 2 variables.

Alternatively, you could do something like:

res = line.split(",")  # split returns list with items: ["Bench", "2750", "3000", "2880"]
key, value = res[0], res[1:]



回答2:


Well a proof of concept:

data = "Bench,2750,3000,2880 Chair,46,70,57 Table,147,152,150"
dic = {}
data = ",".join(data.split(" ")).split(",") #This gets rid of spaces,
#                                            puts commas there and than
#                                            splits everyting up again
print(data)
r,tmp = 1,[]
for i in data:
    if i[0].isalpha():
        if r == 1:
            temp = i
            r = 0
        else:
            dic[temp] = ",".join(tmp.copy())
            temp = i
            tmp.clear()
            r = 0
    else:
        r = 0
        tmp.append(i)
print(dic)

This code can be made a lot better, but this is what i came up with.




回答3:


Based on 0x5453's comment, try this code:

#!/usr/bin/env python3 
sol={}
infile= open("furniture.dat","r")
for line in infile:
     key,*value=line.rstrip().split(",")
     print(f"key = {key},  value = {value}") 
     sol[ key ] = value

I added the python3 shebang up top (since the unpacking feature is in python3 only I've observed just now) and the rstrip() to take the newline off of the last element. I also left my debug code in there for you to review the results.

I've also added a line of code to populate your dictionary.




回答4:


Using zip and list splicing:

my_dict = {}
with open('furniture.dat', 'r') as f:
    for line in f.readlines():
        line_list = line.split(',')
        new_dict = dict(zip(line_list, [(line_list[1:])]))
        my_dict.update(new_dict)
print(my_dict)

Output dictionary: {'bench': ['103', '222', '32'], 'table': ['833', '99', '23'], 'chair': ['83', '22', '882']}



来源:https://stackoverflow.com/questions/61508068/how-to-make-a-file-into-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!