如何在以lst [0] [0]为键的Python中将嵌套列表转换为字典 [英] How to Convert Nested List into dictionary in Python where lst[0][0] is the key
问题描述
我有一个Python 3.x
嵌套列表,如下所示:
I have a Python 3.x
nested list that looks like the following:
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']
如何将上述嵌套列表转换成字典,例如,lst [0] [0]将是字典键,而lst [0] [1:]将是键的值.
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.
此嵌套列表包含数以万计的元素.
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.
对于2.7+版本,您可以使用dict-comp:
You can use a dict-comp for versions 2.7+:
{ k[0]: k[1:] for k in lst }
在2.7(2.6及以下版本)之前,这可以使用内置的dict
完成,例如:
Prior to 2.7 (2.6 and below), this would have been done using the dict
builtin, eg:
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']}
这篇关于如何在以lst [0] [0]为键的Python中将嵌套列表转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!