From f02cd3e40642e38de25134dcb92aec4a38c4d316 Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Fri, 6 Nov 2009 14:44:10 +0100 Subject: [PATCH] add example about trying to swap keys and values in a dictionary with mutable values --- comprehensions.html | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/comprehensions.html b/comprehensions.html index cc9badb..d52bbc1 100644 --- a/comprehensions.html +++ b/comprehensions.html @@ -326,6 +326,16 @@ body{counter-reset:h1 3} >>> {value:key for key, value in a_dict.items()} {1: 'a', 2: 'b', 3: 'c'} +

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. + +

+>>> a_dict = {'a': [1, 2, 3], 'b': 4, 'c': 5}
+>>> {value:key for key, value in a_dict.items()}
+Traceback (most recent call last):
+  File "<stdin>", line 1, in <module>
+  File "<stdin>", line 1, in <dictcomp>
+TypeError: unhashable type: 'list'
+

Set Comprehensions