当前位置: 首页 > 图灵资讯 > 行业资讯> 如何使用python 字典添加数据?

如何使用python 字典添加数据?

来源:图灵python
时间: 2024-12-08 16:32:51

关于python添加的内容并不少,大部分小伙伴都非常喜欢用python去添加内容,根据大家的喜爱程度,给大家又准备了关于添加数据的内容,就是使用字典,小伙伴想不想了解?接下来看下面内容哦~

首先新建一个python文件命名为py3_dict.py,在这个文件中进行字符串操作代码编写(如下为代码,文后有显示运行效果):

#dictionaries是一个Key-Value对形式的集合
#定义一个字典
student={'name':'yale','age':25,'course':['数学','计算机']}
print(student)
print(student['name'])
print(student['course'])
#字典的key和value可定义为immutabledatatype
#例如:定义key为1
student={1:'yale','age':25,'course':['数学','计算机']}
print(student[1])
#访问一个不存在的key
#会出现异常
#KeyError:'phone'
student={'name':'yale','age':25,'course':['数学','计算机']}
#print(student['phone'])
#有时候我们希望不存在的key
#可以返回None或者一个默认值
#用如下方式实现:
print(student.get('phone'))#None
print(student.get('phone','未找到'))#返回默认值:未找到
#往dict字典中添加数据
student={'name':'yale','age':25,'course':['数学','计算机']}
student['phone']='010-55555555'
print(student.get('phone','未找到'))#010-55555555
#改变已存在的key对应的值
student={'name':'yale','age':25,'course':['数学','计算机']}
student['name']='andy'
print(student)
#使用update()改变字典中的多个值
student={'name':'yale','age':25,'course':['数学','计算机']}
student.update({'name':'andy','age':26,'phone':'12345678'})
print(student)
#删除一个key
#使用del关键字
delstudent['phone']
print(student)
#或者使用之前提到过的pop()方法
#删除数据
age=student.pop('age')
print(age)#26
print(student)
#使用len()查看字典中一共有多少key
student={'name':'yale','age':25,'course':['数学','计算机']}
print(len(student))#3
#查看所有的key
print(student.keys())#dict_keys(['name','age','course'])
#查看所有的value
print(student.values())#dict_values(['yale',25,['数学','计算机']])
#查看所有的key和value
#得到一对一对的key-value
#dict_items([('name','yale'),('age',25),('course',['数学','计算机'])])
print(student.items())
#循环字典
#像list的方式循环,打印的是key值
#name
#age
#course
forkeyinstudent:
print(key)
#所以我们用items()方法循环数据:
forkey,valueinstudent.items():
print(key,value)
#结果:
#nameyale
#age25
#course['数学','计算机']

以上代码运行效果:

{'name':'yale','age':25,'course':['数学','计算机']}
yale
['数学','计算机']
yale
None
未找到
010-55555555
{'name':'andy','age':25,'course':['数学','计算机']}
{'name':'andy','age':26,'course':['数学','计算机'],'phone':'12345678'}
{'name':'andy','age':26,'course':['数学','计算机']}
26
{'name':'andy','course':['数学','计算机']}
3
dict_keys(['name','age','course'])
dict_values(['yale',25,['数学','计算机']])
dict_items([('name','yale'),('age',25),('course',['数学','计算机'])])
name
age
course
nameyale
age25
course['数学','计算机']

好啦,如果项目里需要用到以上内容,大家可以参考上面示例,根据自己的需求,设计代码哦~