Skip to content

Commit

Permalink
add example about trying to swap keys and values in a dictionary with…
Browse files Browse the repository at this point in the history
… mutable values
  • Loading branch information
Mark Pilgrim committed Nov 6, 2009
1 parent 50e5f30 commit f02cd3e
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions comprehensions.html
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,16 @@ <h3 id=stupiddicttricks>Other Fun Stuff To Do With Dictionary Comprehensions</h3
<samp class=p>>>> </samp><kbd class=pp>{value:key for key, value in a_dict.items()}</kbd>
<samp class=pp>{1: 'a', 2: 'b', 3: 'c'}</samp></pre>

<p>Of course, this only works if the values of the dictionary are immutable, like strings or tuples. If you try this with a dictionary that contains lists, it will fail most spectacularly.

<pre class=screen>
<samp class=p>>>> </samp><kbd class=pp>a_dict = {'a': [1, 2, 3], 'b': 4, 'c': 5}</kbd>
<samp class=p>>>> </samp><kbd class=pp>{value:key for key, value in a_dict.items()}</kbd>
<samp class=traceback>Traceback (most recent call last):
File "&lt;stdin>", line 1, in &lt;module>
File "&lt;stdin>", line 1, in &lt;dictcomp>
TypeError: unhashable type: 'list'</samp></pre>

<p class=a>&#x2042;

<h2 id=setcomprehension>Set Comprehensions</h2>
Expand Down

0 comments on commit f02cd3e

Please sign in to comment.