Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

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.

like image 585
Mohammed Avatar asked Dec 16 '22 11:12

Mohammed


1 Answers

If I understand you correctly, I think you're after the following.

You can use a dict-comp for versions 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:

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']}
like image 96
Jon Clements Avatar answered Dec 18 '22 12:12

Jon Clements