d = {10:"x", 1:"wx", 2:"yz"}
a = d.setdefault(1)
b = d.setdefault(3)
s = "{}" * len(d)
print(s.format(*d))
为什么输出为11032?
答案 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)
。