[英]Converting list to dictionary with list elements as index - Python
From Python: create dict from list and auto-gen/increment the keys (list is the actual key values)? 从Python:从列表创建dict并自动生成/递增键(列表是实际键值)? , it's possible to create a dict
from a list
using enumerate
to generate tuples made up of incremental keys and elements in life, ie: ,可以使用enumerate
从list
创建dict
,以生成由生活中的增量键和元素组成的元组,即:
>>> x = ['a', 'b', 'c']
>>> list(enumerate(x))
[(0, 'a'), (1, 'b'), (2, 'c')]
>>> dict(enumerate(x))
{0: 'a', 1: 'b', 2: 'c'}
It is also possible to reverse the key-value by iterating through every key in the dict
(assuming that there is a one-to-one mapping between key-value pairs: 还可以通过遍历dict
每个键来反转键值(假设键值对之间存在一对一的映射:
>>> x = ['a', 'b', 'c']
>>> d = dict(enumerate(x))
>>> {v:k for k,v in d.items()}
{'a': 0, 'c': 2, 'b': 1}
Given the input list ['a', 'b', 'c']
, how can achieve the dictionary where the elements as the key and incremental index as values without trying to loop an additional time to reverse the dictionary ? 给定输入列表['a', 'b', 'c']
,如何在不尝试循环额外时间来反转字典的情况下实现将键作为元素并将增量索引作为值的字典 ?
How about simply: 简单地说:
>>> x = ['a', 'b', 'c']
>>> {j:i for i,j in enumerate(x)}
{'a': 0, 'c': 2, 'b': 1}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.