python--字典

1.字典的定义
#字典是一个无序的数据集合,使用print输出字典时
#通常输出的顺序和定义的顺序不一致

users = [‘user1’,‘user2’]
passwd = [‘123’,‘456’]
print(zip(users,passwd))
print(list(zip(users,passwd)))
print(dict(zip(users,passwd)))

s = {}
print(type(s))

#字典:key-value 键值对
#value值可以是任意数据类型

s = {
‘linux’:[100,99,88],
‘westos’:[190,564,645]
}
print(s)
print(type(s))

#工厂函数

d = dict()
print(d)
print(type(d))

d1 = dict(a=1,b=2)
print(d1)
print(type(d1))

#字典的嵌套

students = {
‘05151052’:{
‘name’:‘kk’,
‘age’:18,
‘score’:80
},
‘03113011’:{
‘name’: ‘bad’,
‘age’: 19,
‘score’:30
}
}
print(students[‘05151052’][‘name’])

#所有的key和value值是一样的情况

print({}.fromkeys({‘1’,‘2’},‘05151052’))

2.字典的特性
d = {
‘1’:‘a’,
‘2’:‘b’
}

#字典不支持索引

print(d[‘1’])

#字典不支持切片

print(d[:])

#字典的重复和连接无意义,因为字典的key值是唯一的

#成员操作符

print(‘1’ in d)
print(‘1’ not in d)

#for循环,默认遍历字典的key值

for key in d:
print(key)

#遍历字典

for key in d:
print(key,d[key])

for key,value in d.items():
print(key,value)

3.字典的增加
service = {
‘http’:80,
‘ftp’:21,
‘ssh’:22
}

#增加一个元素
#如果key值存在,则更新对应的value值
#如果key值不存在,则添加对应的key-value值

service[‘mysql’] = 3306
print(service)
service[‘http’] = 443
print(service)

#添加多个key-value值
service_backup = {
‘https’:443,
‘tomcat’:8080,
‘http’:8080
}

service.update(service_backup)
print(service)
service.update(flask=9000,http=8000)
print(service)

#setdefault添加key值
#如果key值存在,不做修改
#如果key值不存在,则添加对应的key-value

service.setdefault(‘http’,9090)
print(service)
service.setdefault(‘oracle’,44575)
print(service)

4.字典的删除
service = {
‘http’:80,
‘ftp’:21,
‘ssh’:22
}

del service[‘http’]
print(service)

#pop删除指定key的key-value
#如果key存在,删除,并且返回删除key对应的value
#如果key不存在,报错

item = service.pop(‘http’)
print(item)
print(service)

#popitem删除最后一个key-value值

item = service.popitem()
print(‘删除的key-value对是:’,item)
print(service)

#清空字典内容

service.clear()
print(service)

5.字典的查看
service = {
‘http’:80,
‘ftp’:21,
‘ssh’:22
}

#查看字典的key值

print(service.keys())

#查看字典的value值

print(service.values())

#查看key的value值;key不存在,报错

print(service[‘https’])

#查看key的value值
#key不存在,默认返回None
#key不存在,有default,则返回default

print(service.get(‘https’,443))
print(service.get(‘https’))

#遍历

for k,v in service.items():
print(k,’—>’,v)
print(service[‘https’])
if ‘https’ in service:
print(service[‘https’])
else:
print(‘key not exist’)

#get方法获取指定key对应的value值
#如果key值存在,返回对应的value值
#如果key值不存在,默认返回None,如果需要指定返回值,传值即可

print(service.get(‘https’,‘ket not exist’))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值