[英]Read the csv file store data in nested dictionary
我有像这样的 csv 文件 [image][1][1]: https://i.stack.imgur.com/kaBMF.png 它有 2 列,我读过这个 Z628CB5675FF524F3E719B7A2E 文件并存储在下面的数据字典中,8我的代码
import csv
with open('p1.csv', mode='r') as infile:
reader = csv.reader(infile)
mydict = {rows[0]:rows[1] for rows in reader}
pprint(mydict)
上面的代码行给了我 output 如下:
{'00:00-00:15': '266.78',
'00:15-00:30': '266.78',
'00:30-00:45': '266.78',
'00:45-01:00': '266.78',
'01:00-01:15': '266.78',}
但我想要这个 output 格式如下:
{{'00:00-00:15': '266.78'},
{'00:15-00:30': '266.78'},
{'00:30-00:45': '266.78'},
{'00:45-01:00': '266.78'},
{'01:00-01:15': '266.78'}}
这应该有效。 在rows[0]:rows[1]
周围放置额外的括号以创建多个字典。 请记住,您想要的 output (这给出了)是一set
字典( {1, 2, 3}
是设置文字表示法)。 您可能想要使用列表,将外部{}
替换为[]
import csv
with open('p1.csv', mode='r') as infile:
reader = csv.reader(infile)
mydict = [{rows[0]:rows[1]} for rows in reader]
pprint(mydict)
您想要的似乎是一set
字典,但这是不可能的,因为字典不可散列。 您可以通过定义自己的dict
子类来解决该限制。
import csv
import hashlib
from pprint import pprint
class HashableDict(dict):
""" Hashable dict subclass. """
def __hash__(self):
m = hashlib.sha256(b''.join(bytes(repr(key_value), encoding='utf8')
for key_value in self.items()))
return int.from_bytes(m.digest(), byteorder='big')
with open('p1.csv', mode='r', newline='') as infile:
mydict = {HashableDict({row[0]:row[1]}) for row in csv.reader(infile)}
pprint(mydict, sort_dicts=False)
Output:
{{'00:00-00:15': '266.78'},
{'00:15-00:30': '266.78'},
{'00:30-00:45': '266.78'},
{'00:45-01:00': '266.78'},
{'01:00-01:15': '266.78'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.