定义字典:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}获取字典中的值
PRint ("dict['Name']: ",dict['Name'])print ("dict['Age']: ",dict['Age'])结果:
dict['Name']: Zaradict['Age']: 7注意点:如果代码改为
print ("dict['Name']: "+dict['Name'])print ("dict['Age']: "+dict['Age'])会报如下错误:
dict['Name']: Zara print ("dict['Age']: "+dict['Age'])TypeError: Can't convert 'int' object to str implicitly错误原因,数字不能和字符串进行’+’号连接 我们可以使用str(dict[‘Age’])进行强制转换
print ("dict['Name']: "+dict['Name'])print ("dict['Age']: "+str(dict['Age']))实验结果:
dict['Name']: Zaradict['Age']: 7在字典中添加list
grade={'math':{'yingshu':['yangmi','luoyang','yuzhenchang'],'xinxi':['wenping','kangjing','jinwei']},'tongji':{'tongji':['A','B','C'],'jingsuan':['E','F','G']}}获取数据:
print(grade['math']['yingshu'][0])实验结果:
yangmi修改数据:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}dict['Age'] = 8; # update existing entryprint ("dict['Age']: ", dict['Age'])实验结果:
dict['Age']: 8添加新的记录项:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}dict['School'] = "DPS School"; # Add new entryprint ("dict['School']: ", dict['School'])实验结果:
dict['School']: DPS School删除记录:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}del dict['Name']; # 删除键是'Name'的条目print(dict['Name'])运行结果会报错:
print(dict['Name'])KeyError: 'Name'清空词典所有条目和删除词典
新闻热点
疑难解答