学python字典的时候遇到了这么一个小问题:当执行遍历字典命令的时候,报错:

TypeError: can only concatenate str (not “int”) to str

后来研究了一下,举例一下代码:

qingyunian_people = {
‘name’: ‘fanxian’,
‘male_or_female’: ‘male’,
‘age’: 30,
‘family’: ‘ruoruo’,
}
print(qingyunian_people)
for key,value in qingyunian_people.items():
print(‘\nkey:’ + key)
 print(‘value:’ + value)

问题出在这个上面这个value值里面,因为键(key)age对应的值(value)是一个数值30,是一个int(整数)与 + 前的类型不一致,加号前是一个字符串str,需要将其也转换为字符串的形式,或者把字典里面的age键的值也改成字符串。

ps:如果这个值是30.00,则会提示:

can only concatenate str (not “float”) to str

 

反正就是类型不对计算机罢工了……

两种解决办法:

第一种:

‘age’: 30,

更改为:

‘age’: ’30’,

第二种:

for key,value in qingyunian_people.items():
print(‘\nkey:’ + key)
 print(‘value:’ + value)

改为:

for key,value in qingyunian_people.items():
print(‘\nkey:’ + str(key))
 print(‘value:’ + str(value))

这样保持一致的类型就可以打印了………………

 

 

延伸:

那我这么改其实也可以运行:

qingyunian_people = {
‘name’: 12345,
‘male_or_female’: 0,
‘age’: 30,
‘family’: 11,
}
print(qingyunian_people)
for key,value in qingyunian_people.items():
print(‘\nkey:’ + key)
print(30 + value)

23333333开个玩笑