Search code examples
python-3.xlistdictionaryenumerate

Using enumerate within a dictionary comprehension of a nested list


Is there an elegant/pythonic method for creating a dictionary from a nested list with enumerate, that enumerates at the sublist level rather that at the list-of-lists level?

Please consider this example:

nested_list = [["ca", "at"], ["li", "if", "fe"], ["ca", "ar"]]

I have tried to convert it into a dictionary that looks like this:

# Desired output.
# {'ca': 0, 'at': 1, 'li': 2, 'if': 3, 'fe': 4, 'ar': 5}

Here is my best attempt, but it appears to enumerate the list at the upper level and overwrite the value for duplicate keys - which is undesirable.

item_dict = {item: i for i, item in enumerate(nested_list) for item in item}
# Current output.
# {'ca': 2, 'at': 0, 'li': 1, 'if': 1, 'fe': 1, 'ar': 2}

Am I better off splitting this task into an un-nesting step, and then a dictionary comprehension step?

All insight is appreciated, thank you.


Solution

  • I think I've solved it, but it's quite ugly...

    {key: i for i, key in enumerate(set([item for item in nested_list for item in item]))}
    # Output.
    {'if': 0, 'at': 1, 'fe': 2, 'li': 3, 'ca': 4, 'ar': 5}