Converting tuple of lists of variable length into dictionary

Peter Otten __peter__ at web.de
Sun Oct 18 08:47:11 EDT 2015


Beppe wrote:

> 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

The above code will work without changes in Python 2.7. For older Python 
versions you can replace the dict comprehension with a generator expression:

>>> d = dict(
... (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']}

I have no Python below 2.7 ready to test, but this version should work for 
Python 2.4 and above. If you find explict loops easier to understand:

>>> d = {}
>>> for items in lists:
...     for i, c in enumerate(items):
...             assert c not in d
...             d[c] = items[:i] + items[i+1:]
... 

should work for Python 2.3 and above (untested). I have smuggled in an 
assertion that checks for duplicate keys.





More information about the Python-list mailing list