{"id":112017,"date":"2020-04-25T15:48:10","date_gmt":"2020-04-25T15:48:10","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=7917"},"modified":"2020-04-25T15:48:10","modified_gmt":"2020-04-25T15:48:10","slug":"how-to-convert-a-list-of-list-to-a-dictionary-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/04\/25\/how-to-convert-a-list-of-list-to-a-dictionary-in-python\/","title":{"rendered":"How to Convert a List of List to a Dictionary in Python?"},"content":{"rendered":"<p>For some applications, it&#8217;s quite useful to convert a list of lists into a dictionary. <\/p>\n<ul>\n<li><strong>Databases<\/strong>: List of list is table where the inner lists are the database rows and you want to assign each row to a primary key in a new dictionary. <\/li>\n<li><strong>Spreadsheet<\/strong>: List of list is two-dimensional spreadsheet data and you want to assign each row to a key (=row name). <\/li>\n<li><strong>Data Analytics<\/strong>: You&#8217;ve got a two-dimensional matrix (=<a href=\"https:\/\/blog.finxter.com\/collection-10-best-numpy-cheat-sheets-every-python-coder-must-own\/\" target=\"_blank\" rel=\"noreferrer noopener\">NumPy array<\/a>) that&#8217;s initially represented as a list of list and you want to obtain a <a href=\"https:\/\/blog.finxter.com\/how-to-convert-two-lists-into-a-dictionary\/\">dictionary <\/a>to ease data access.<\/li>\n<\/ul>\n<p>There are three main ways to convert a list of lists into a dictionary in Python (<a rel=\"noreferrer noopener\" href=\"https:\/\/www.8bitavenue.com\/how-to-convert-list-of-lists-to-dictionary-in-python\/\" target=\"_blank\">source<\/a>):<\/p>\n<ol>\n<li>Dictionary Comprehension<\/li>\n<li>Generator Expression<\/li>\n<li>For Loop<\/li>\n<\/ol>\n<p>Let&#8217;s dive into each of those.<\/p>\n<h2>1. Dictionary Comprehension<\/h2>\n<p><strong>Problem<\/strong>: Say, you&#8217;ve got a<a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-list-of-lists\/\" target=\"_blank\"> list of lists<\/a> where each list represents a person and consists of three values for the person&#8217;s name, age, and hair color. For convenience, you want to create a dictionary where you use a person&#8217;s name as a dictionary key and the sublist consisting of the age and the hair color as the dictionary value.<\/p>\n<p><strong>Solution<\/strong>: You can achieve this by using the beautiful (but, surprisingly, little-known) feature of <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-dictionary\/\" target=\"_blank\">dictionary comprehension<\/a> in Python.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">persons = [['Alice', 25, 'blonde'], ['Bob', 33, 'black'], ['Ann', 18, 'purple']] persons_dict = {x[0]: x[1:] for x in persons}\nprint(persons_dict)\n# {'Alice': [25, 'blonde'],\n# 'Bob': [33, 'black'],\n# 'Ann': [18, 'purple']}<\/pre>\n<p><strong>Explanation<\/strong>: The dictionary comprehension statement consists of the expression <code>x[0]: x[1:]<\/code> that assigns a person&#8217;s name <code>x[0]<\/code> to the list <code>x[1:]<\/code> of the person&#8217;s age and hair color. Further, it consists of the context <code>for x in persons<\/code> that iterates over all &#8220;data rows&#8221;. <\/p>\n<p><strong>Exercise<\/strong>: Can you modify the code in our interactive code shell so that each hair color is used as a key and the name and age are used as the values?<\/p>\n<p> <iframe loading=\"lazy\" height=\"700px\" width=\"100%\" src=\"https:\/\/repl.it\/@finxter\/listoflists2dict?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"><\/iframe> <\/p>\n<p>Modify the code and click the &#8220;run&#8221; button to see if you were right!<\/p>\n<h2>2. Generator Expression<\/h2>\n<p>A similar way of achieving the same thing is to use a generator expression in combination with the dict() constructor to create the dictionary. <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">persons = [['Alice', 25, 'blonde'], ['Bob', 33, 'black'], ['Ann', 18, 'purple']] persons_dict = dict((x[0], x[1:]) for x in persons)\nprint(persons_dict)\n# {'Alice': [25, 'blonde'],\n# 'Bob': [33, 'black'],\n# 'Ann': [18, 'purple']}<\/pre>\n<p>This code snippet is almost identical to the one used in the &#8220;list comprehension&#8221; part. The only difference is that you use tuples rather than direct mappings to fill the dictionary.<\/p>\n<h2>3. For Loop<\/h2>\n<p>Of course, there&#8217;s no need to get fancy here. You can also use a regular <a href=\"https:\/\/blog.finxter.com\/python-one-line-for-loop-a-simple-tutorial\/\" target=\"_blank\" rel=\"noreferrer noopener\">for loop<\/a> and define the dictionary elements one by one within a simple for loop. Here&#8217;s the alternative code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">persons = [['Alice', 25, 'blonde'], ['Bob', 33, 'black'], ['Ann', 18, 'purple']] persons_dict = {}\nfor x in persons: persons_dict[x[0]] = x[1:] print(persons_dict)\n# {'Alice': [25, 'blonde'],\n# 'Bob': [33, 'black'],\n# 'Ann': [18, 'purple']}\n<\/pre>\n<p>Again, you map each person&#8217;s name to the list consisting of its age and hair color. <\/p>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?<\/p>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>For some applications, it&#8217;s quite useful to convert a list of lists into a dictionary. Databases: List of list is table where the inner lists are the database rows and you want to assign each row to a primary key in a new dictionary. Spreadsheet: List of list is two-dimensional spreadsheet data and you want [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-112017","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/112017","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=112017"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/112017\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=112017"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=112017"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=112017"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}