简体   繁体   中英

Read the csv file store data in nested dictionary

I have csv file like this [image][1][1]: https://i.stack.imgur.com/kaBMF.png which has 2 columns, I have read this csv file and stored data in dictionary, below is my code

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)

This above lines of code gives me output as follows:

{'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',}

But i want this output in below form:

     {{'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'}}

This should work. Put extra brackets around rows[0]:rows[1] to create multiple dictionaries. Keep in mind, the output you want (and this gives) is a set of dictionaries ( {1, 2, 3} is set literal notation). You might want to use a list, by replacing the outer {} with []

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)

What you want appears to be a set of dictionaries, however that's impossible because dictionaries aren't hashable. You can workaround that restriction by defining your own dict subclass which is.

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'}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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