Reputation: 734
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!
Upvotes: 2
Views: 216
Reputation: 51
You can use the dictionary "setdefault" method ( which can be replaced in many cases by using the defaultdict - but not always - I like the setdefault as its more general and quite powerful )
Use cases for the 'setdefault' dict method
def process( data ):
result = {}
for vals in data:
result.setdefault( vals[0], [] ).append( vals[1:] )
return result
Also, mathsaey's answer
{line[0] : [tup[1:] for tup in data if tup[0] == line[0]] for line in data}
is wrong as the values of his dictionary are list of lists rather than list of values. I don't have enough reputation to comment (new account), so adding this observation here.
Upvotes: 0
Reputation: 180481
If all the tuples have 4 elements, you could just unpack the tuples:
my_d = {}
for k, v1, v2, v3 in l:
if my_d.get(k):
my_d[k] += [(v1,v2,v3)]
else:
my_d[k] = [(v1,v2, v3)]
Upvotes: 0
Reputation: 129537
I would use a collections.defaultdict
:
def preparer_donnees(data):
from collections import defaultdict
ret = defaultdict(list)
for v in data:
ret[v[0]].append(v[1:])
return ret
Upvotes: 4
Reputation: 78
You could use a nested list comprehension:
{line[0] : [tup[1:] for tup in data if tup[0] == line[0]] for line in data}
Upvotes: 0