温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用python字典添加数据的示例

发布时间:2020-11-09 09:29:49 来源:亿速云 阅读:283 作者:小新 栏目:编程语言

这篇文章将为大家详细讲解有关使用python字典添加数据的示例,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

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

#dictionaries 是一个Key-Value对形式的集合
#定义一个字典
student = {'name':'yale','age':25,'course':['数学','计算机']}
print(student)
print(student['name'])
print(student['course'])
#字典的key和value可定义为immutable data type
#例如:定义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 关键字
del student['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
for key in student:
 print(key)
#所以我们用items()方法循环数据:
for key,value in student.items():
 print(key,value)
#结果:
#name yale
#age 25
#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
name yale
age 25
course ['数学', '计算机']

关于使用python字典添加数据的示例就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI