Converting tuple of lists of variable length into dictionary

Peter Otten __peter__ at web.de
Sun Oct 18 07:00:05 EDT 2015


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']}





More information about the Python-list mailing list