append()

dict在使用append()函数的时候必须是原本的dict中有相应的key,不然只能用dict[key]=XXX,即原先的dict中有这个key,才能对这个key进行append,理解为append是针对list的就对了

错误:

test_dict={}
a="a"
b="b"
for i in range(2):
    test_dict["x"].append(a)
print(test_dict)

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-46-672451699641> in <module>
      3 b="b"
      4 for i in range(2):
----> 5     test_dict["x"].append(a)
      6 print(test_dict)

KeyError: 'x'

正确:

test_dict={"x":[1]}
a="a"
b="b"
for i in range(2):
    test_dict["x"].append(a)
print(test_dict)


{'x': [1, 'a', 'a']}

顺便说一下  +

+是针对同种类型的操作,list和int不能,前后都是list就可以

猜你喜欢

转载自blog.csdn.net/qq_30468133/article/details/84996184