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



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016