[英]How to format a list of dictionaries from CSV? - Python
I have a CSV file of stock price data that I would like to put into a dictionary containing the Date and Close price. 我有一个股票价格数据CSV文件,我想将其放入包含日期和收盘价的字典中。
Here is what the CSV looks like: date close volume open high low 2017/09/22 151.89 46575410 152.02 152.27 150.56 2017/09/21 153.39 37350060 155.8 155.8 152.75 2017/09/20 156.07 52126240 157.9 158.26 153.83 2017/09/19 158.73 20565620 159.51 159.77 158.44
CSV看起来像这样:
date close volume open high low 2017/09/22 151.89 46575410 152.02 152.27 150.56 2017/09/21 153.39 37350060 155.8 155.8 152.75 2017/09/20 156.07 52126240 157.9 158.26 153.83 2017/09/19 158.73 20565620 159.51 159.77 158.44
I would like the end dictionary to be arranged like this: 我希望这样安排最终字典:
perfect_dict = [
{'Date': '2017/09/22', 'Close': '151.89'},
{'Date': '2017/09/21', 'Close': '153.39'},
...]
My current code grabs the CSV data and creates two separate lists for the dates and the close prices. 我当前的代码获取CSV数据,并为日期和收盘价创建两个单独的列表。 I've tried using
dict(zip(dates, close_prices)
but that doesn't format the new dictionary the way I mentioned above. This is my code: 我已经尝试使用
dict(zip(dates, close_prices)
但这并没有像我上面提到的那样格式化新字典。这是我的代码:
import csv
from collections import defaultdict
# --->
columns = defaultdict(list)
with open('mydata.csv') as f:
reader = csv.DictReader(f)
for row in reader: value2,...}
for (k,v) in row.items():
columns[k].append(v)
dates = columns['date']
close_prices = columns['close']
# This is what doesn't format it right
#stock_dict = dict(zip(dates, close_prices))
#pprint.pprint(stock_dict)
If anyone could point me in the right direction that would be awesome, thanks! 如果有人能指出我正确的方向,那就太好了,谢谢!
You can use dictionary comprehension: 您可以使用字典理解:
import csv
data = list(csv.reader(open('filename.csv')))
final_data = [{a:b for a, b in zip(["Date", "Close"], i[:2])} for i in data[1:]]
Note that you cannot store the dictionaries in a set as the dictionaries themselves are unhashable. 请注意,您无法将字典存储在集合中,因为字典本身是不可散列的。
I don't think the format you are aiming for is possible - do you mean to say that you want a list of dictionaries? 我认为您所针对的格式不可行-您是说要列出词典吗? As written, this is a dictionary of dictionaries but the outer dictionary does not have any keys.
如所写,这是字典的词典,但外部词典没有任何键。
Additionally, if you want to set the value for a given dictionary key, you may want to do something like: 此外,如果要为给定的字典键设置值,则可能需要执行以下操作:
columns[k] = v
EDIT: 编辑:
Does this get closer to what you're looking for? 这是否更接近您的需求? Instantiate columns as an empty list, and then format each row of your csv as a dictionary and append to that list.
将列实例化为空列表,然后将csv的每一行设置为字典格式并追加到该列表。
columns = []
with open('mydata.csv') as f:
reader = csv.DictReader(f)
for row in reader:
row_as_dict = {k: v for k, v in row.items()}
columns.append(row_as_dict)
By using pandas
to read the csv file
通过使用
pandas
读取csv file
date
and close
column and store as a list date
并close
列并存储为列表 The code 编码
import pandas as pd
df = pd.read_csv("file_name.csv")
# read the date and close column and store as a list.
time_list = list(df['date'])
close_list = list(df['close'])
perfect_dict = []
# here take the minimum length
# because avoiding index error
take_length = min(len(time_list),len(close_list))
for i in range(take_length):
temp_dict={}
temp_dict["Date"]=time_list[i]
temp_dict["Close"] = close_list[i]
perfect_dict.append(temp_dict)
print(perfect_dict)
The another possible way. 另一种可能的方式。
import csv
perfect_dict=[]
with open('file.csv') as f:
reader = list(csv.reader(f))
for row in reader[1:]:
temp_dict = {}
temp_dict["Date"] = row[0]
temp_dict["Close"] = row[1]
perfect_dict.append(temp_dict)
print(perfect_dict)
Maybe a litte late, but you may try the following solution with a "normal" csv reader and transform the data later on: 也许晚了一点,但是您可以使用“普通”的csv阅读器尝试以下解决方案,并在以后转换数据:
columns = list()
with open('mydata.csv') as f:
reader = list(csv.reader(f))
header = reader[0]
for row in reader[1:]:
temp_dict = dict()
for idx, item in enumerate(row):
if idx < 2:
temp_dict[header[idx]] = item
columns.append(new_dict)
Assuming your csv is structured as you presented (header as first row and the order of columns), the code converts a raw csv input into a list of dictionaries. 假设您的csv的结构如您所展示的(标题为第一行,列的顺序),则代码会将原始的csv输入转换为字典列表。 Moreover,
idx < 2
ensures that only "date" and "close" is mapped to the new output. 此外,
idx < 2
确保只有“日期”和“关闭”被映射到新输出。
If you prefer capitalised column headers, just add header = list(map(lambda x: x.capitalize(), header))
after line 4. 如果您喜欢大写的列标题,只需在第4行之后添加
header = list(map(lambda x: x.capitalize(), header))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.