read from file into a dictionary which value is a tuple

Question:

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

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?

Asked By: maria

||

Answers:

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

Answered By: Fred
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.