z3ugma
z3ugma

Reputation: 63

Mapping (key, value) (key, value) to (key, (value1, value2)) in Python

I have a list of tuples of the form (User, Page):

tuples = [(Tim, PageFoo), (Jen,PageBar), (Tim, PageBaz), ...]

I want to loop over this list and create a new list or dict of pages per user:

newlist = [(Tim,[PageFoo, PageBaz]), (Jen, [PageBar]), ...]

The problem I'm having is that these pages aren't in order by user - as I loop, I need to check newlist to see if the User already exists, and if so, update the list.

Can anyone help me get through my mental block?

Upvotes: 2

Views: 1176

Answers (2)

m.wasowski
m.wasowski

Reputation: 6387

@Aशwini चhaudhary was faster, but here is defaultdict solution:

from collections import defaultdict

tuples = [('Tim', 'PageFoo'), ('Jen','PageBar'), ('Tim', 'PageBaz')]
result = defaultdict(list)
for key, value in tuples:
    result[key].append(value)
result
# Out[8]: defaultdict(<type 'list'>, {'Tim': ['PageFoo', 'PageBaz'], 'Jen': ['PageBar']})
dict(result)
# Out[9]: {'Jen': ['PageBar'], 'Tim': ['PageFoo', 'PageBaz']} 
result.items()
# Out[10]: [('Tim', ['PageFoo', 'PageBaz']), ('Jen', ['PageBar'])]

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

You can use collections.OrderedDict for this, if order doesn't matter then go for collections.defaultdict:

from collections import OrderedDict
tuples = [('Tim', 'PageFoo'), ('Jen', 'PageBar'), ('Tim', 'PageBaz')]
d = OrderedDict()
for k, v in tuples:
    d.setdefault(k, []).append(v)

>>> d.items()
[('Tim', ['PageFoo', 'PageBaz']), ('Jen', ['PageBar'])]

Upvotes: 2

Related Questions