+ 6
[Solved] Dictionary comprehension
d = {k:v for k, v in ('a1', 'b2')} print(d) >>> {'a' : '1' , 'b' : '2'}
3 Réponses
+ 6
Variable <k> and <v> are getting their values from each character in string 'a1' and 'b2' respectively, in each comprehension loop iteration.
How this works is similar to how the following lines work:
a, b = ( 10, 20 ) # a = 10, b = 20
c, d = 'KO' # c = 'K', d = 'O'
+ 7
Siavash Kardar Tehran ,
this kind of dict comprehension does only work if the both strings inside the tuple contains exactly 2 characters each.
if we use the code like this:
d = {k:v for k, v in ('a12', 'b27')} # (strings now contain 3 characters)
is used, or strings contains only 1 character, we get a ValueError, and unpack procedure fails