views:

607

answers:

2

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.

+14  A: 
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}
MizardX
+17  A: 

Same idea as MizardX, but slightly smaller and prettier in Python 3.0 using dict comprehensions:

>>> names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']]
>>> names_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}
Kiv