字典的创建,特性,增加,删除以及修改与查看

1.字典的创建
以key-value 键值对存储的一种数据结构
#value值可以是任意数据类型:int float long list set tuple dict
d = {
‘1’:‘a’,
‘8’:‘b’,
‘2’:‘a’
}
字典的嵌套
students = {
‘xuehao’:{
‘name’:‘zhangsan’,
‘age’:18,
‘score’:90
},
‘xuehao1’:{
‘name’:‘lisi’,
‘age’:18,
‘score’:88
},
}
print(students[‘xuehao’][‘name’])

注意:字典不支持索引和切片,字典的重复和连接是无意义的,字典的key是唯一的

字典的操作符:判断的是某个值是否为字典的key

d = {
‘1’:‘a’
‘8’:‘b’
}
print(‘1’ in d)
print(‘2’ not in d)
print(d[‘1’]) #其实输出的是key值对应value
工厂函数
d5 = dict(a=1,b=2)
print(d5)
字典的for循环,默认遍历字典的key值
for key in d5:
print(key) 遍历输出字典的key值
遍历字典
for key in d5:
print(key,d5[key]) 遍历输出字典的key-value值
在这里插入图片描述

service = {
‘http’:80,
‘ftp’:21,
‘ssh’:22
}

1,增加一个元素

1),如果key值存在,则更新对应的value值
2),如果key值不存在,则添加对应的key-value值
service[‘mysql’]=3306
service[‘http’]=32
print(service)
2,添加多个key-value值
1),如果key值存在,则更新对应的value值
2),如果key值不存在,则添加对应的key-value值
service={
‘tomact’:8080,
‘https’:43,
‘http’:888
}
service.update(flask=9000,http=222)
print(service)
3.setdefault添加key值:
1),如果key值存在,则不做修改
2),如果key值不存在,则添加对应的key-value值
service.setdefault(‘httpd’,9000)
print(service)

1,删除字典中的内容
1)del关键字
del service[‘http’]
print(‘service’)
2,pop删除指定key的key-value值
1)如果key存在,删除,(并且返回删除key对应的value值)
2)如果key不存在,直接报错
item = service.pop(‘http’)
print(item) 可以打印出删除的key对应的value值
print(service)
在这里插入图片描述
3.popitem删除最后一个key-value
item1=service.popitem()
print(service)

4.清空字典内容
service.clear()
print(service)

查看字典里面所有的key值

print(service.keys())

查看字典里面所有的value值

print(service.values())

查看指定key对应的value值

print(service[‘http’])
#遍历字典
for k,v in service.items():
print(k,’—>’,v)

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

print(service.get(‘https’))

fromkeys
用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。第一个参数可以是 list/tuple/str/set
fromkeys()方法语法:

dict.fromkeys(seq,[value])

seq = (‘name’, ‘age’, ‘sex’)
dict = dict.fromkeys(seq, 10)
print (“新的字典为 : %s” % str(dict))
输出结果为
新的字典为 : {‘age’: 10, ‘name’: 10, ‘sex’: 10}

猜你喜欢

转载自blog.csdn.net/qq_43279936/article/details/84563982