Read the csv file store data in nested dictionary

I have csv file like this [image][1][1]: https://i.sstatic.net/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'}}

Upvotes: 1

Views: 216

Answers (2)

martineau
martineau

Reputation: 123473

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

Upvotes: 1

mazore
mazore

Reputation: 1024

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)

Upvotes: 1

Related Questions