Python: Convert list to dictionary with indexes as values

后端 未结 5 1948
傲寒
傲寒 2020-12-02 16:08

I am trying to convert the following list:

list = [\'A\',\'B\',\'C\']

To a dictionary like:

dict = {\'A\':0, \'B\':1, \'C\'         


        
相关标签:
5条回答
  • 2020-12-02 16:51

    You have to convert the unhashable list into a tuple:

    dct = {tuple(key): idx for idx, key in enumerate(lst)}
    
    0 讨论(0)
  • 2020-12-02 16:59

    Use built-in functions dict and zip :

    >>> lst = ['A','B','C']
    >>> dict(zip(lst,range(len(lst))))
    
    0 讨论(0)
  • 2020-12-02 17:08

    You can get the indices of a list from the built-in enumerate. You just need to reverse the index value map and use a dictionary comprehension to create a dictionary

    >>> lst = ['A','B','C']
    >>> {k: v for v, k in enumerate(lst)}
    {'A': 0, 'C': 2, 'B': 1}
    

    Ohh, and never name a variable to a built-in or a type.

    0 讨论(0)
  • 2020-12-02 17:09

    Don't use list as your variable name because it's reserved by Python. You can also take advantage of enumerate.

    your_list = ['A', 'B', 'C']
    dict = {key: i for i, key in enumerate(your_list)}
    
    0 讨论(0)
  • 2020-12-02 17:11

    Python dict constructor has an ability to convert list of tuple to dict, with key as first element of tuple and value as second element of tuple. To achieve this you can use builtin function enumerate which yield tuple of (index, value).

    However question's requirement is exact opposite i.e. tuple should be (value, index). So this requires and additional step to reverse the tuple elements before passing to dict constructor. For this step we can use builtin reversed and apply it to each element of list using map

    >>> lst = ['A', 'B', 'C']
    >>> dict(map(reversed, enumerate(lst)))
    >>> {'A': 0, 'C': 2, 'B': 1}
    
    0 讨论(0)
提交回复
热议问题