Thursday, 15 May 2014

Intersect multiple lists in a dictonary using python -



Intersect multiple lists in a dictonary using python -

this has been bugging me whole day. need send emails different person, emails may have multiple recipients, , recipient receives multiple emails.

so suppose have dictionary this:

{ 'email4': ['msg1', 'msg4', 'msg5'], 'email2': ['msg1', 'msg3'], 'email3': ['msg1', 'msg2', 'msg4'], 'email1': ['msg1', 'msg2', 'msg3'] }

and want produce like:

{ 'email1, email2, email3, email4': ['msg1'], 'email1, email3': ['msg2'], 'email1, email2': ['msg3'], 'email3, email4': ['msg4'], 'email4': ['msg5'] }

i figured multiple intersection on both keys , values of dictionary sort of thing, anyway, idea.

quick question, how do in python.

thanks help, have nice day.

update why utilize email(s) keys let's i'm gonna send email email address 4, instead of sending msg1, msg4, , msg5 in separate emails, want combine them 1 email. tuple keys it's demonstration, of course of study can utilize tuples, how's gonna solve problem?

thanks all

example using defaultdict of sets intermediate info structure:

#!/usr/bin/env python # encoding: utf-8 collections import defaultdict pprint import pprint messages = { 'email4': ['msg1', 'msg4', 'msg5'], 'email2': ['msg1', 'msg3'], 'email3': ['msg1', 'msg2', 'msg4'], 'email1': ['msg1', 'msg2', 'msg3'] } intermediate = defaultdict(set) email, msgs in messages.items(): msg in msgs: intermediate[msg].add(email) inverted = {tuple(v): k k, v in intermediate.items()} pprint(inverted) # {('email2', 'email1'): 'msg3', # ('email3', 'email1'): 'msg2', # ('email4',): 'msg5', # ('email4', 'email2', 'email3', 'email1'): 'msg1', # ('email4', 'email3'): 'msg4'}

python

No comments:

Post a Comment