+ 6

[Solved] Dictionary comprehension

d = {k:v for k, v in ('a1', 'b2')} print(d) >>> {'a' : '1' , 'b' : '2'}

24th May 2022, 7:40 AM
Siavash Kardar Tehran
Siavash Kardar Tehran - avatar
3 Answers
+ 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'
24th May 2022, 9:22 AM
Ipang
+ 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
24th May 2022, 9:35 AM
Lothar
Lothar - avatar
+ 6
Thank you so much Ipang and Lothar . ā¤šŸŒ¹
24th May 2022, 2:53 PM
Siavash Kardar Tehran
Siavash Kardar Tehran - avatar