Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Can a Python Dictionary Have a List as a Value?

#1
Can a Python Dictionary Have a List as a Value?

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;789184&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</div>
<h2>Question</h2>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: Can you use lists <em>as values</em> of a dictionary in Python?</p>
<p>This short article will answer your question. So, let’s get started right away with the answer:</p>
<h2>Answer</h2>
<p class="has-global-color-8-background-color has-background">You can use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank">Python lists</a> as dictionary values. In fact, you can use arbitrary Python objects as <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="post" data-id="5232" target="_blank">dictionary</a> values and all <a rel="noreferrer noopener" href="https://blog.finxter.com/python-__hash__-magic-method/" data-type="post" data-id="38118" target="_blank">hashable</a> objects as dictionary keys. You can define a list <code>[1, 2]</code> as a dict value either with <code>dict[key] = [1, 2]</code> or with <code>d = {key: [1, 2]}</code>.</p>
<p>Here’s a concrete example showing how to create a dictionary <code>friends</code> where each dictionary value is in fact a list of friends:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1,2,3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">friends = {'Alice': ['Bob', 'Carl'], 'Bob': ['Alice'], 'Carl': []} print('Alice friends: ', friends['Alice'])
# Alice friends: ['Bob', 'Carl'] print('Bob friends: ', friends['Bob'])
# Bob friends: ['Alice'] print('Carl friends: ', friends['Carl'])
# Carl friends: []</pre>
<p>Note that you can also assign lists as values of specific keys by using the <a href="https://blog.finxter.com/python-dictionary-how-to-create-add-replace-retrieve-remove/" data-type="post" data-id="36698" target="_blank" rel="noreferrer noopener">dictionary assignment</a> operation like so:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2,3,4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">friends = dict()
friends['Alice'] = ['Bob', 'Carl']
friends['Bob'] = ['Alice']
friends['Carl'] = [] print('Alice friends: ', friends['Alice'])
# Alice friends: ['Bob', 'Carl'] print('Bob friends: ', friends['Bob'])
# Bob friends: ['Alice'] print('Carl friends: ', friends['Carl'])
# Carl friends: []
</pre>
<h2>Can I Use Lists as Dict Keys?</h2>
<p class="has-global-color-8-background-color has-background">You cannot use lists as dictionary keys because lists are <a href="https://blog.finxter.com/mutable-vs-immutable-objects-in-python/" data-type="post" data-id="204090" target="_blank" rel="noreferrer noopener">mutable</a> and therefore not <a href="https://blog.finxter.com/python-__hash__-magic-method/" data-type="post" data-id="38118" target="_blank" rel="noreferrer noopener">hashable</a>. As dictionaries are built on hash tables, all keys must be hashable or Python raises an <a href="https://blog.finxter.com/how-to-fix-typeerror-unhashable-type-list/" data-type="post" data-id="465745" target="_blank" rel="noreferrer noopener">error message</a>.</p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">d = dict()
my_list = [1, 2, 3]
d[my_list] = 'abc'
</pre>
<p>This leads to the following error message:</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="">Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 3, in &lt;module> d[my_list] = 'abc'
TypeError: unhashable type: 'list'</pre>
<p class="has-global-color-8-background-color has-background">To fix this, <a href="https://blog.finxter.com/convert-list-to-tuple/" data-type="post" data-id="7862" target="_blank" rel="noreferrer noopener">convert the list to a Python tuple</a> and use the Python tuple as a dictionary key. Python tuples are immutable and hashable and, therefore, can be used as set elements or dictionary keys.</p>
<p>Here’s the same example after converting the list to a <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="post" data-id="12043" target="_blank" rel="noreferrer noopener">tuple</a>—it works! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f389.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">d = dict()
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
d[my_tuple] = 'abc'
</pre>
<p>Before you go, maybe you want to join our free <a href="https://blog.finxter.com/email-academy/" data-type="page" data-id="12278" target="_blank" rel="noreferrer noopener">email academy</a> of ambitious learners like you? The goal is to become 1% better every single day (as a coder). We also have cheat sheets! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>
</div>


https://www.sickgaming.net/blog/2022/10/...s-a-value/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016