mardi 3 juin 2014

Python: transform list of tuples in dictionary


Vote count:

0




Wondering if there is a more idiomatic (pythonic) way of doing this. I have a list of tuples returned by a cursor object, and I'm trying to regroup the data in a dictionary. The data I get is formatted as such:



[("Département d'informatique", 119, 74, 193),
("Département d'informatique", 193, 67, 260),
("Département de chimie", 355, 44, 399) ... ]


Notice that departments repeat. Each line with the same department represents a different kind of data. I need to regroup that data in a dictionary that contains a key (department name) and the value would be a list of all the tuples that have that department as its first member. So something like this:



{ "Département d'informatique": [(119, 74, 193), (193,67,260) ...] }


Here is my code. It's working at the moment but I'm not sure if it's the most efficient/pythonic way of doing things.



def preparer_donnees(data):
ret = { ligne[0] : [] for ligne in data }

for ligne in data:
for entree in ligne[1:]:
ret[ligne[0]].append(entree)

return ret


Thanks!



asked 31 secs ago






Aucun commentaire:

Enregistrer un commentaire