Create an account


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

#1
Dict to List — How to Convert a Dictionary to a List in Python

<div><p class="has-black-color has-luminous-vivid-amber-background-color has-text-color has-background"><strong>Summary</strong>: To convert a dictionary to a list of tuples, use the <code>dict.items()</code> method to obtain an iterable of <code>(key, value)</code> pairs and convert it to a list using the <code>list(...)</code> constructor: <code>list(dict.items())</code>. To modify each key value pair before storing it in the list, you can use the list comprehension statement <code>[(k', v') for k, v in dict.items()]</code> replacing <code>k'</code> and <code>v'</code> with your specific modifications.</p>
<p>In my code projects, I often find that choosing the right data structure is an important prerequisite to writing clean and effective code. In this article, you’ll learn the most Pythonic way to <em>convert a <a href="https://blog.finxter.com/python-dictionary/" title="Python Dictionary – The Ultimate Guide" target="_blank" rel="noreferrer noopener">dictionary </a>to a <a href="https://blog.finxter.com/python-lists/" title="The Ultimate Guide to Python Lists" target="_blank" rel="noreferrer noopener">list</a></em>.</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Dict to List — How to Convert a Dictionary to a List in Python" width="1400" height="788" src="https://www.youtube.com/embed/LD5vqxyIpMM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Problem</strong>: Given a dictionary of <code>key:value</code> pairs. Convert it to a list of <code>(key, value)</code> tuples.</p>
<p><strong>Example</strong>: Given the following 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="">d = {'Alice': 19, 'Bob': 23, 'Carl': 47}</pre>
<p>You want to convert it to a list of <code>(key, value)</code> tuples:</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="">[('Alice', 19), ('Bob', 23), ('Carl', 47)]</pre>
<p>You can get a quick overview of the methods examined in this article next:</p>
<p> <iframe src="https://trinket.io/embed/python/63517365f5" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Change the data structure of the dictionary elements. Does it still work?</em></p>
<p>Let’s dive into the methods!</p>
<h2>Method 1: List of Tuples with dict.items() + list()</h2>
<figure class="wp-block-image size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/dict_to_lists-1024x576.jpg" alt="dict to list python" class="wp-image-10211" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/dict_to_lists-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
<p>The first approach uses the dictionary method <code>dict.items()</code> to retrieve an iterable of <code>(key, value)</code> tuples. The only thing left is to convert it to a list using the built-in <code>list()</code> constructor.</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="">d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 1
t = list(d.items())
print(t)
# [('Alice', 19), ('Bob', 23), ('Carl', 47)]</pre>
<p>The variable <code>t</code> now holds a list of <code>(key, value)</code> tuples. Note that in many cases, it’s not necessary to actually convert it to a list, and, thus, instantiate the data structure in memory. For example, if you want to loop over all <code>(key, value)</code> pairs in the dictionary, you can do so without conversion:</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="">for k,v in d.items(): s = str(k) + '->' + str(v) print(s) '''
Alice->19
Bob->23
Carl->47 '''</pre>
<p>Using the <code>items()</code> method on the dictionary object is the most Pythonic way if everything you want is to retrieve a list of <code>(key, value)</code> pairs. However, what if you want to get a list of keys—ignoring the values for now?</p>
<h2>Method 2: List of Keys with dict.key()</h2>
<p>To get a list of key values, use the <code>dict.keys()</code> method and pass the resulting iterable into a <code>list()</code> constructor.</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="">d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 2
t = list(d.keys())
print(t)
# ['Alice', 'Bob', 'Carl']</pre>
<p>Similarly, you may want to get a list of values.</p>
<h2>Method 3: List of Values with dict.values()</h2>
<p>To get a list of key values, use the <code>dict.values()</code> method and pass the resulting iterable into a <code>list()</code> constructor.</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="">d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 3
t = list(d.values())
print(t)
# [19, 23, 47]</pre>
<p>But what if you want to modify each <code>(key, value)</code> tuple? Let’s study some alternatives.</p>
<h2>Method 4: List Comprehension with dict.items()</h2>
<p><a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener" title="List Comprehension in Python — A Helpful Illustrated Guide">List comprehension</a> is a compact way of creating lists. The simple formula is <code>[expression + context]</code>.</p>
<ul>
<li><strong>Expression: </strong>What to do with each list element?</li>
<li><strong>Context:</strong> What elements to select? The context consists of an arbitrary number of <code>for</code> and <code>if</code> statements.</li>
</ul>
<p>You can use list comprehension to modify each <code>(key, value)</code> pair from the original dictionary before you store the result in the new list.</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="">d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 4
t = [(k[:3], v-1) for k, v in d.items()]
print(t)
# [('Ali', 18), ('Bob', 22), ('Car', 46)]</pre>
<p>You transform each key to a string with three characters using <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank" rel="noreferrer noopener" title="Introduction to Slicing in Python">slicing </a>and reduce each value by one.</p>
<h2>Method 5: zip() with dict.keys() and dict.values()</h2>
<p>Just for comprehensibility, you could (theoretically) use the <a href="https://blog.finxter.com/zip-unzip-python/" target="_blank" rel="noreferrer noopener" title="Zip &amp; Unzip: How Does It Work in Python?"><code>zip()</code> function </a>to create a <a href="https://blog.finxter.com/how-to-merge-lists-into-a-list-of-tuples/" target="_blank" rel="noreferrer noopener" title="How to Merge Lists into a List of Tuples? [6 Pythonic Ways]">list of tuples</a>:</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="">d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 5
t = list(zip(d.keys(), d.values()))
print(t)
# [('Alice', 19), ('Bob', 23), ('Carl', 47)]
</pre>
<p>However, there’s no benefit compared to just using the <code>dict.items()</code> method. However, I wanted to show you this because the <code><a href="https://blog.finxter.com/python-ziiiiiiip-a-helpful-guide/" target="_blank" rel="noreferrer noopener" title="Python Ziiiiiiip! [A helpful guide]">zip()</a></code> function is frequently used in Python and it’s important for you to understand it. </p>
<h2>Method 6: Basic Loop</h2>
<p>The last method uses a basic for <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">loop</a>—not the worst way of doing it! Sure, a Python pro would use the most Pythonic ways I’ve shown you above. But using a basic for loop is sometimes superior—especially if you want to be able to customize the code later (e.g., increasing the complexity of the loop body). </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="">d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 6
t = []
for k, v in d.items(): t.append((k,v))
print(t)
# [('Alice', 19), ('Bob', 23), ('Carl', 47)]
</pre>
<p>A <a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" title="Python One Line For Loop [A Simple Tutorial]" target="_blank" rel="noreferrer noopener">single-line for loop</a> or <a href="https://blog.finxter.com/which-is-faster-list-comprehension-or-map-function-in-python/" title="Which is Faster: List Comprehension or Map Function in Python?" target="_blank" rel="noreferrer noopener">list comprehension</a> statement is not the most Pythonic way to convert a dictionary to a Python list if you want to modify each new list element using a more complicated body expression. In this case, a straightforward for loop is your best choice!</p>
<p><strong>Related articles:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/list-to-dict-convert-a-list-into-a-dictionary-in-python/" title="List to Dict — Convert a List Into a Dictionary in Python" target="_blank" rel="noreferrer noopener">List to Dict Conversion</a></li>
<li><a href="https://blog.finxter.com/how-to-convert-a-list-of-list-to-a-dictionary-in-python/" title="How to Convert a List of List to a Dictionary in Python?" target="_blank" rel="noreferrer noopener">How to Convert a List of List to a Dictionary in Python?</a></li>
<li><a href="https://blog.finxter.com/python-dictionary/" target="_blank" rel="noreferrer noopener" title="Python Dictionary – The Ultimate Guide">Ultimate Guide to Dictionaries</a></li>
<li><a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">Ultimate Guide to Lists</a></li>
</ul>
<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>
</p>
</p></p>
</div>


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



Forum Jump:


Users browsing this thread:
3 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016