Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

read from file into a dictionary which value is a tuple

i have this file called chocolates.txt:

Mary;dark;0.5
Steve;dark;0.5
Mary;toffee;2
Mary;white;0.25
Steve;raspberry;1
Mary;milk;1.25

i have to write a code read_data that returns a dictionary like this:
>>>read_data('chocolates.txt') {'Mary':[('dark', 0.5), ('toffee', 2.0), ('white, 0.25), ('milk', 1.25)], 'Steve': [('dark', 0.5), ('raspberry': 1.0)]}'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

so the dictionary values are lists of tuples.
I tried to do something like this (so that first I put all the data into sets and then turn them into tuples but my code doesn’t work.

def read_data(file):
d = {}
f = open(file, encoding='utf-8')
for row in file:
    x = row.strip().split(";")
    buyer = x[0]
    if not buyer in d:
        d[buyer] = set()
        kd[buyer].add(x[1:])
    f.close()
    return d`

Is there another way to do that?

>Solution :

You don’t need to use sets for this.

Open the file and read one line at a time. Strip any leading/traing whitespace. Split on semi-colon (expect 3 tokens).

Use setdefault to append to a list keyed by the "buyer"

def read_data(file):
    d = {}
    with open(file) as data:
        for line in map(str.strip, data):
            buyer, v, n = line.split(';')
            d.setdefault(buyer, []).append((v, float(n)))
    return d

…should do what you need

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading