为什么输出为11032? Python3.6

时间:2018-03-06 04:36:34

标签: python dictionary python-3.6

d = {10:"x", 1:"wx", 2:"yz"}
a = d.setdefault(1)
b = d.setdefault(3)
s = "{}" * len(d)
print(s.format(*d))

为什么输出为11032?

1 个答案:

答案 0 :(得分:2)

在2次setdefault调用后,

d = {10: "x", 1: "wx", 2: "yz"}
d.setdefault(1)  # does not change the dictionary because there's already 1
d.setdefault(3)  # add 3 with value None (default if not speicfied)

d变为:

>>> d
{10: 'x', 1: 'wx', 2: 'yz', 3: None}

迭代字典产生字典键:10, 1, 2, 3。 (由*d执行迭代以解包参数d):

>>> for key in d:
...     print(key)
... 
10
1
2
3

因此,s.format(*d)相当于'{}{}{}{}'.format(10, 1, 2, 3)