create a dictionary from a text file, which contains a key and a set made from multiple properties

4066 views python

The text file contains the names of cheeses and its properties. The number of properties is not the same for each cheese. An end result is a dictionary with the names of each cheese being a key and its properties being the set linked to that key.

Is there a different way than manually copying each set of properties into a set and assigning the correct key?

champignon de luxe garlic,soft,soft-ripened,garlicky,herbaceous,herbal,spicy,cream,creamy,natural
bleu dauvergne,semi-soft,artisan,buttery,creamy,grassy,herbaceous,salty,spicy,tangy,strong,ivory,creamy and smooth,bloomy

answered question

There is no python in this question.

1 Answer


import csv

with open(filename) as cheeses:
    cheese_rows = csv.reader(cheeses)
    d = {cheese_row[0]: set(cheese_row[1:]) for row in cheese_rows}

This will create a dictionary with keys of the first value in each row in the file, and values of a set of the rest of values in the row.

posted this

Have an answer?


Please login first before posting an answer.