Python Golf: The most concise way to turn 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 checks, but I could not get it to work with nested lists. I could use a nested loop like:

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 to do this.

+3
source share
3 answers
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}
+14
source

Same 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}
+19

python 2.6

dict([(t,l.index(x)) for x in l for t in x])

python3.0

{t:l.index(x) for x in l for t in x}

l -

+1

Source: https://habr.com/ru/post/1703008/


All Articles