9.Python字典
In [1]:
#空字典
dict1 = {}
dict2 = dict()
#非空字典定义
dict3 = {'ID': '123456789', 'name' : 'lucky', 'age' : '18'}
#列表可以转列表,但是前提是列表中的元素都要成对出现
#dict4 = dict(('name', 'lucky')) #ValueError: dictionary update sequence element #0 has length 4; 2 is required
dict4 = dict([('name', 'lucky')])
dict5 = dict([('name', 'lucky'),('age', '18')])
In [2]:
dict2 = {'name':'tom', 'age':'18', 'gender':'man'}
In [3]:
#增
dict6 = {}
dict6['brand'] = 'huawei'
dict6['type'] = 'p30 pro'
dict6['price'] = 9000
dict6['color'] = '黑色'
print(dict6)
In [4]:
#改
dict6['brand'] = 'mi'
print(dict6)
In [5]:
# 案例:用户注册功能
#模拟数据库
database = []
print('--------------------欢迎来到智联招聘-------------------------')
Isanswer = True
while Isanswer:
#定义一个字典
user = {}
username = input('输入用户名:')
password = input('请输入密码:')
repassword = input('请输入确定密码:')
#将信息保存到字典中
user['username'] = username
if password == repassword:
user['password'] = password
else:
print('两次密码不一致!')
continue
email = input('请输入邮箱:')
phone = input('请输入手机号码:')
user['email'] = email
user['phone'] = phone
#保存数据到数据库中
database.append(user)
Isanswer = input('是否继续注册?(y/n)')
if Isanswer != 'y':
break
print(database)
In [6]:
#查:通过key来取值
print(dict6['color'])
In [7]:
#遍历:拿到字典的key
for i in dict6:
print(i)
In [8]:
dict6 = {'数学': 100,'语文': 96, '英语': 99}
In [9]:
#items():转换为元组
print(dict6.items())
for key, value in dict6.items():
print(key, value)
In [10]:
#values():取出字典中所有的值
result = dict6.values()
print(result)
#求总平均分
scores = dict6.values()
totle = sum(scores)
avg = totle / len(scores)
print('平均分:', avg)
In [11]:
#keys():获取字典所有key键
project = dict6.keys()
print(project)
In [12]:
dict6 = {'张三':'100', '李四':'96', '王五':'99', '赵六':'93'}
del dict6['李四']
print(dict6)
result = dict6.pop('王五','error') #根据key删除字典中的键值对,返回值是:只要删除成功,则返回对应的key值,否则返回设定的默认值
print(dict6)
print(result)
result = dict6.pop('没有','无')
print(dict6)
print(result)
版权所有
http://www.cnblogs.com/King-Penguin
posted on 2020-01-06 15:37 King-Penguin 阅读(277) 评论(0) 编辑 收藏 举报