Converting tuple of lists of variable length into dictionary

Beppe giuseppecostanzi at gmail.com
Sun Oct 18 08:23:49 EDT 2015


Il giorno domenica 18 ottobre 2015 13:00:44 UTC+2, Peter Otten ha scritto:
> Beppe wrote:
> 
> > hi to everybody, I must turn a tuple of lists into a dictionary.
> > 
> > something like
> > 
> > (['a', 'b', 'c', 'd', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n', 'o'])
> > 
> > note that the length af each list is variable
> > 
> > must return
> > 
> > a ['b', 'c', 'd', 'e', 'f']
> > b ['a', 'c', 'd', 'e', 'f']
> > c ['a', 'b', 'd', 'e', 'f']
> > d ['a', 'b', 'c', 'e', 'f']
> > e ['a', 'b', 'c', 'd', 'f']
> > f ['a', 'b', 'c', 'd', 'e']
> > g ['h', 'i']
> > h ['g', 'i']
> > i ['g', 'h']
> > l ['m', 'n', 'o']
> > m ['l', 'n', 'o']
> > n ['l', 'm', 'o']
> > o ['l', 'm', 'n']
> 
> What do you want to do with items that occur in more than one list?
> 
> If there are no such duplicate items it's easy:
> 
> >>> lists = (['a', 'b', 'c', 'd', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 
> 'n', 'o'])
> >>> d = {
> ... c: items[:i] + items[i+1:]
> ... for items in lists
> ... for i, c in enumerate(items)
> ... }
> >>> pprint.pprint(d)
> {'a': ['b', 'c', 'd', 'e', 'f'],
>  'b': ['a', 'c', 'd', 'e', 'f'],
>  'c': ['a', 'b', 'd', 'e', 'f'],
>  'd': ['a', 'b', 'c', 'e', 'f'],
>  'e': ['a', 'b', 'c', 'd', 'f'],
>  'f': ['a', 'b', 'c', 'd', 'e'],
>  'g': ['h', 'i'],
>  'h': ['g', 'i'],
>  'i': ['g', 'h'],
>  'l': ['m', 'n', 'o'],
>  'm': ['l', 'n', 'o'],
>  'n': ['l', 'm', 'o'],
>  'o': ['l', 'm', 'n']}

hi Peter, you are right, no duplicates are admitted between lists,
anyway your solution,works on python 3 but not on 2.
however beautiful list comprehension solution.
I will try to suit it for the python version i need
regards
beppe



More information about the Python-list mailing list