0
d = {k:v for k, v in ('a1', 'b2')} d['a1'] = 1 d['b2'] = 2 print(d) print(len(d))
Can some one explain this code
2 Antworten
+ 7
Akash Yadav ,
the first line is a dict comprehension that uses a tuple of strings as an iterable.
these strings will be unpacked to the variables k = key and v = value, and thenn added to the dict.
after this statement the result is: {'a': '1', 'b': '2'}
in the next 2 steps 2 new key / value pairs will created in the dict
then dict will be printed and also the length of the dict
+ 5
d = {k:v for k, v in ('a1', 'b2')}
# d == {'a': '1', 'b': '2'}
# ("a1" is a string [or an array of chars] w/ 2 values: a & 1)
d['a1'] = 1
# d == {'a': '1', 'b': '2', "a1": 1}
d['b2'] = 2
# d == {'a': '1', 'b': '2', "a1": 1, "b2": 2}
print(d)
print(len(d))
# d has 4 keys so output: 4