Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Convert a List of List to a Dictionary in Python?

#1
How to Convert a List of List to a Dictionary in Python?

<div><p>For some applications, it’s quite useful to convert a list of lists into a dictionary. </p>
<ul>
<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>
<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>
<li><strong>Data Analytics</strong>: You’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’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>
</ul>
<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>
<ol>
<li>Dictionary Comprehension</li>
<li>Generator Expression</li>
<li>For Loop</li>
</ol>
<p>Let’s dive into each of those.</p>
<h2>1. Dictionary Comprehension</h2>
<p><strong>Problem</strong>: Say, you’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’s name, age, and hair color. For convenience, you want to create a dictionary where you use a person’s name as a dictionary key and the sublist consisting of the age and the hair color as the dictionary value.</p>
<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>
<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}
print(persons_dict)
# {'Alice': [25, 'blonde'],
# 'Bob': [33, 'black'],
# 'Ann': [18, 'purple']}</pre>
<p><strong>Explanation</strong>: The dictionary comprehension statement consists of the expression <code>x[0]: x[1:]</code> that assigns a person’s name <code>x[0]</code> to the list <code>x[1:]</code> of the person’s age and hair color. Further, it consists of the context <code>for x in persons</code> that iterates over all “data rows”. </p>
<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>
<p> <iframe 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>
<p>Modify the code and click the “run” button to see if you were right!</p>
<h2>2. Generator Expression</h2>
<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>
<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)
print(persons_dict)
# {'Alice': [25, 'blonde'],
# 'Bob': [33, 'black'],
# 'Ann': [18, 'purple']}</pre>
<p>This code snippet is almost identical to the one used in the “list comprehension” part. The only difference is that you use tuples rather than direct mappings to fill the dictionary.</p>
<h2>3. For Loop</h2>
<p>Of course, there’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’s the alternative code:</p>
<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 = {}
for x in persons: persons_dict[x[0]] = x[1:] print(persons_dict)
# {'Alice': [25, 'blonde'],
# 'Bob': [33, 'black'],
# 'Ann': [18, 'purple']}
</pre>
<p>Again, you map each person’s name to the list consisting of its age and hair color. </p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<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>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>


https://www.sickgaming.net/blog/2020/04/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How to Convert MIDI to MP3 in Python – A Quick Overview xSicKxBot 0 1,135 09-02-2023, 02:04 PM
Last Post: xSicKxBot
  [Tut] The Most Pythonic Way to Get N Largest and Smallest List Elements xSicKxBot 0 920 09-01-2023, 03:23 AM
Last Post: xSicKxBot
  [Tut] List Comprehension in Python xSicKxBot 0 868 08-23-2023, 07:54 PM
Last Post: xSicKxBot
  [Tut] Collections.Counter: How to Count List Elements (Python) xSicKxBot 0 840 08-19-2023, 06:03 AM
Last Post: xSicKxBot
  [Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python xSicKxBot 0 670 08-16-2023, 08:49 AM
Last Post: xSicKxBot
  [Tut] Sort a List, String, Tuple in Python (sort, sorted) xSicKxBot 0 780 08-15-2023, 02:08 PM
Last Post: xSicKxBot
  [Tut] Python Converting List of Strings to * [Ultimate Guide] xSicKxBot 0 643 05-02-2023, 01:17 PM
Last Post: xSicKxBot
  [Tut] Python List of Tuples to DataFrame ? xSicKxBot 0 659 04-22-2023, 06:10 AM
Last Post: xSicKxBot
  [Tut] Dictionary of Lists to DataFrame – Python Conversion xSicKxBot 0 692 04-17-2023, 03:46 AM
Last Post: xSicKxBot
  [Tut] Python List of Dicts to Pandas DataFrame xSicKxBot 0 728 04-11-2023, 04:15 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016