简体   繁体   English

Python - append 列表项到字典中的不同键

[英]Python - append items of list to different keys in dictionary

I have data from a.csv file that is as follows (the real file contains much more data).我有来自 a.csv 文件的数据,如下所示(真实文件包含更多数据)。 The first row that I'm showing contains the labels for each column, and the rest of the lines contain temperature data for each location.我显示的第一行包含每一列的标签,而行的 rest 包含每个位置的温度数据。 There is also a header before this data that I did not include so the top row of the.csv file does not contain the labels.在此数据之前还有一个 header 我没有包含,因此.csv 文件的第一行不包含标签。

Scan,location1,location2,location3
1,32.621,38.57,36.977
2,30.976,38.451,36.971
3,32.599,38.536,36.991

What I want to do is to create a dictionary of lists where the keys are the labels (top row) and the value is a list of all temperatures for each label.我想要做的是创建一个列表字典,其中键是标签(顶行),值是每个 label 的所有温度的列表。 So the output I'm looking for is this...所以我要找的output就是这个……

{"scan":[1,2,3], "location1":[32.621,30.976,32.599], "location2":[38.57,38.451,38.536], "location3":[36.977,36.971,36.991]}

I have successfully created a list of the keys and a dictionary which contains empty lists as values.我已经成功创建了一个键列表和一个包含空列表作为值的字典。 I am having a problem in me 'else' statement where all temperature data on each line goes into each key of the dictionary.我在我的“其他”语句中遇到问题,每行上的所有温度数据都进入字典的每个键。 How can I get each element of the line_data list to be appended to a different key in my data dictionary?如何将 line_data 列表的每个元素附加到我的数据字典中的不同键?

import csv
from tkinter.filedialog import askopenfilename

csv_file_name = askopenfilename(title='Select the temperature file you want to analyze')
file = open(csv_file_name, 'r')
read_file = file.readlines()
keys = []
for line in read_file:
    # Column titles will be dictionary keys
    if keys == []:
        keys = line.split(",")
        data = dict.fromkeys(keys, [])
    else:
        line_data = line.split(",")
        for i in range(len(line_data)):
            data[keys[i]].append(line_data[i])

Use pandas to read CSV file and further can be processed through dictionary processing.使用 pandas 读取 CSV 文件,可以进一步通过字典处理。

import pandas as pd

df = pd.read_csv('sales.csv')

res_dict = {col:list(df[col].values) for col in df.columns}

print(res_dict)

Output: Output:

{'Scan': [1, 2, 3], 'location1': [32.621, 30.976, 32.599000000000004], 'location2': [38.57, 38.451, 38.536], 'location3': [36.977, 36.971, 36.991]}

Going with your approach, You are passing [] to dict.fromkeys function which means all values in the dictionary will be pointing to same list object.按照您的方法,您将 [] 传递给dict.fromkeys function,这意味着字典中的所有值都将指向同一个列表 object。

Find the below code to make it correct:找到以下代码以使其正确:

import csv
from tkinter.filedialog import askopenfilename

csv_file_name = askopenfilename(title='Select the temperature file you want to analyze')
file = open(csv_file_name, 'r')
read_file = file.readlines()
keys = []
for line in read_file:
    # Column titles will be dictionary keys
    if keys == []:
        keys = line.split(",")
        data={keys[k]:[] for k in range(len(keys))} # **you can initialise a dict like this**
        # data = dict.fromkeys(keys, []) # -- Don't do this!!
    else:
        line_data = line.split(",")
        for i in range(len(line_data)):
            data[keys[i]].append(line_data[i])
print(data)

Hope this helps!希望这可以帮助!

Is this what you are looking for?这是你想要的?

df
Out[9]: 
   Scan  location1  location2  location3
0     1     32.621     38.570     36.977
1     2     30.976     38.451     36.971

df.to_dict('list')
Out[12]: 
{'Scan': [1, 2],
 'location1': [32.621, 30.976],
 'location2': [38.57, 38.451],
 'location3': [36.977, 36.971]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM