Search code examples
pythoncode-golf

Python Golf: what's the most concise way of turning this list of lists into a dictionary:


I have a list of lists that looks like this:

[['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']]

and I want to turn it into a dictionary where each key is a name and each value is a number corresponding to the position of its sublist in the list:

{'Tom': 0, 'Dick': 0, 'Harry': 1, 'John': 1, 'Mike': 1, 'Bob': 2}

I tried various list comprehensions, but I couldn't get it to work right with the nested lists. I could use a nested loop, like this:

names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']]
names_dict = {}
for i, name_sublist in enumerate(names):
    for name in name_sublist:
        names_dict[name] = i

but I suspect there is a shorter, more elegant way of doing it.


Solution

  • names_dict = dict((name,index)
                      for index,lst in enumerate(names)
                      for name in lst)
    

    Example:

    >>> names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']]
    >>> names_dict = dict((name,index)
    ...                   for index,lst in enumerate(names)
    ...                   for name in lst)
    >>> names_dict
    {'Tom': 0, 'Mike': 1, 'Dick': 0, 'Harry': 1, 'Bob': 2, 'John': 1}