[英]How to Convert Nested List into dictionary in Python where lst[0][0] is the key
I have a Python 3.x
nested list that looks like the following: 我有一个
Python 3.x
嵌套列表,如下所示:
lst = [['kataba', 'V:', '3rd_sg_masc_perf_active'], ['kataba:', 'V:', '3rd_dual_masc_perf_active'], ['katabu:', 'V:', '3rd_pl_masc_perf_active'], ['katabat', 'V:', '3rd_sg_fm_perf_active'], ['katabata:', 'V:', '3rd_dual_fm_perf_active']]
I will slice one instance so that my question will be clearer 我将切一个实例,以便我的问题更加清楚
>>> lst[0]
['kataba', 'V:', '3rd_sg_masc_perf_active']
>>> lst[0][0]
'kataba'
>>> lst[0][1:]
['V:', '3rd_sg_masc_perf_active']
How to convert the above nested list into a dictionary where, for example, lst[0][0] will be the dictionary key, and lst[0][1:] will be the value of the key. 如何将上述嵌套列表转换成字典,例如,lst [0] [0]将是字典键,而lst [0] [1:]将是键的值。
This nested list contains tens of thousands of elements. 此嵌套列表包含数以万计的元素。
Could you help me, because I have tried many options but it seems that I don't have the logic to do it. 您能帮我吗,因为我尝试了很多选择,但似乎我没有这样做的逻辑。
If I understand you correctly, I think you're after the following. 如果我对您的理解正确,我认为您是在遵循以下条件。
You can use a dict-comp for versions 2.7+: 您可以将dict-comp用于2.7+版本:
{ k[0]: k[1:] for k in lst }
Prior to 2.7 (2.6 and below), this would have been done using the dict
builtin, eg: 在2.7(2.6及更低版本)之前,这将使用内置的
dict
完成,例如:
dict( (k[0], k[1:]) for k in lst)
# {'kataba': ['V:', '3rd_sg_masc_perf_active'], 'katabat': ['V:', '3rd_sg_fm_perf_active'], 'katabata:': ['V:', '3rd_dual_fm_perf_active'], 'katabu:': ['V:', '3rd_pl_masc_perf_active'], 'kataba:': ['V:', '3rd_dual_masc_perf_active']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.