How to Convert Nested List into dictionary in Python where lst[0][0] is the key
16,911
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']}
Related videos on Youtube
Author by
Mohammed
Ph.D. Student in Computational Linguistics, Central Institute of Indian Languages, Mysore - India.
Updated on July 07, 2022Comments
-
Mohammed almost 2 years
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.
-
jamylak about 11 years+1 But I would make the first suggestion the dict-comp since this is Py3K and the alternative for Py<=2.6 the old style one, second
-
Jon Clements about 11 years@jamylak not quite sure why I put it that way around tbh! But good point - I'll swap 'em
-
Mohammed about 11 years@JonClements Many many thanks to you! This really works magic. The above line is what I was exactly looking for. However, I want to ask one more question: how can I learn such magical lines and tricks? Is there any resourcebook for such codes?
-
Mohammed about 11 years@jamylak Many thanks to you for your kind attention to my problem. Both of Jon and you are very nice people. I feel grateful to you!
-
Jon Clements about 11 years@mohammed the terms to lookup are "slicing" and "dictionary comprehension" - that'll give you a good starting point. Good luck with Python.