I have a CSV file I'd like to parse as a Dict, so that the first item with the key of "key" can be unpacked to a variable, then the rest of the values as a list of keyed languages. Is there a nice, clean way of doing this?
My CSV is like so:
key,english,spanish
wanna_play_a_game,"Wanna play a game?","¿Quiero jugar a un juego?"
something_else,"Hello!","hola!"
Dict object as such:
[{'key': 'wanna_play_a_game', 'english': 'Wanna play a game?', 'spanish': '¿Quiero jugar a un juego?'}, {'key': 'something_else', 'english': 'Hello', 'spanish': 'hola!'}]
I did have a go but then realised that unpacking isn't the same with dicts (I assume) because they're not ordered like with lists. Am I overcomplicating things and should just saved the row['key']
to a variable and then remove it from the dict? Python isn't my bread & butter language so I'm not that knowledgable on the more magicky bits of the syntax.
This is what I was kinda getting at before realising I'm lost:
import csv
class Translate:
def __init__(self):
self.translations = self.readCSV('translations.csv')
def readCSV(self, filename):
with open(filename, 'rt') as csvfile:
reader = csv.DictReader(csvfile)
return [dict(d) for d in reader]
def parse(self, line):
# for t_key, *langs in self.translations:
# for k, (t_key, *langs) in self.translations:
# ... some magic function?
The basic thing I'm trying to get is t_key
to be "wanna_play_a_game"
and langs
to be ('english': 'Wanna play a game?', 'spanish': '¿Quiero jugar a un juego?')