Create an account


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

#1
How to Create a List of Dictionaries in Python?

<div><p><iframe height="400px" width="100%" src="https://repl.it/@finxter/listofdicts?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><strong>Problem</strong>: Say, you have a <a href="https://blog.finxter.com/python-dictionary/" target="_blank" rel="noreferrer noopener" title="Python Dictionary – The Ultimate Guide">dictionary </a><code>{0: 'Alice', 1: 'Bob'}</code> and you want to create a <a href="https://blog.finxter.com/merge-dictionaries/" target="_blank" rel="noreferrer noopener" title="Python How to Join a List of Dictionaries into a Single One?">list of dictionaries</a> with <a href="https://blog.finxter.com/python-list-copy/" target="_blank" rel="noreferrer noopener" title="Python List copy()">copies </a>of the original dictionary: <code>[{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]</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="">d = {0: 'Alice', 1: 'Bob'} dicts = [{**d} for _ in range(3)]
print(dicts)
# [{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]</pre>
<p>You use<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> with a “throw-away” <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">loop </a>variable underscore <code>_</code> to create a list of 3 elements. You can change the value 3 if you need more or fewer elements in your <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">list</a>. </p>
<p>The expression <code>{**d}</code> unpacks all (key, value) pairs from the original dictionary <code>d</code> into a new dictionary. <a href="https://blog.finxter.com/what-is-asterisk-in-python/" target="_blank" rel="noreferrer noopener" title="What is the Asterisk / Star Operator (*) in Python?">For more information about the unpacking operator, see this Finxter blog tutorial. </a></p>
<p>The resulting list contains copies of the original dictionary. If you change one, the others won’t see that change:</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="">dicts[0][2] = 'Frank'
print(dicts)
# [{0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]</pre>
<p>Only the first dictionary in the list contains the new key value pair <code>(2: 'Frank')</code> which proves that the dictionaries don’t point to the same object in memory. This would be the case if you’d use the following method of <a href="https://blog.finxter.com/copy-list-of-lists-in-python-shallow-vs-deep/" target="_blank" rel="noreferrer noopener" title="How to Copy List of Lists in Python (Shallow vs Deep)?">copying a list</a> with a single 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="">d2 = {0: 'Alice', 1: 'Bob'} dicts2 = [d2] * 3
print(dicts2)
# [{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]</pre>
<p>The method looks right but all three dictionaries are essentially the same:</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="">dicts2[0][2] = 'Frank'
print(dicts2)
# [{0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob', 2: 'Frank'}]
</pre>
<p>If you change one, you change all.</p>
<p>You can see this effect yourself in the following memory visualizer tool:</p>
<p> <iframe src="https://pythontutor.com/iframe-embed.html#code=d2%20%3D%20%7B0%3A%20'Alice',%201%3A%20'Bob'%7D%0A%0Adicts2%20%3D%20%5Bd2%5D%20*%203%0Aprint%28dicts2%29%0A%0Adicts2%5B0%5D%5B2%5D%20%3D%20'Frank'%0Aprint%28dicts2%29&amp;codeDivHeight=400&amp;codeDivWidth=350&amp;cumulative=false&amp;curInstr=1&amp;heapPrimitives=nevernest&amp;origin=opt-frontend.js&amp;py=3&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false" width="800" height="500" frameborder="0"> </iframe> </p>
<p><em><strong>Exercise</strong>: change the method to the correct one so that the change affects only the first dictionary!</em></p>
<p><strong>Related articles</strong>: <a href="https://blog.finxter.com/how-to-create-a-python-list/" target="_blank" rel="noreferrer noopener" title="How to Create a Python List?">How to create a Python list?</a></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/07/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016