python基础-字典

字典:具有 键值对 映射关系的一组 无序 的数据组合
key: value key不变、value可以随意改变
通过key,来找到对应的value
关键字:dict
标识符:{}
注意:key是唯一的,且不能改变,通常喜欢用str
无序:没有下标/索引/index
"""
dic = {
"name": "七夜",
"sno": 231,
"cls": [231, 230, 229, 228]
}
print(dic)
print(type(dic)) # <class 'dict'>

字典的增删改:
新增:字典的变量名["字典中 不存在 的key"] = 值 -- 向字典中添加一组键值对
修改:字典的变量名["字典中 存在 的key"] = 值 -- 把原有字典的value换成新的
删除:通过key删除且key不能为空 dic.pop("name")
删除:通过key删除且key不能为空 del dic["name"]
删除:从后往前删除 dic.popitem()
清空:dic.clear()
len()测量字典中,键值对的个数
keys:返回一个包含字典所有KEY的列表。
values:返回一个包含字典所有value的列表
items:返回一个包含所有(键,值)元祖的列表
info = {'name': '冯八一', 'age': 33, 'sex':'男'}
print(info.keys()) # dict_keys(['name', 'sex', 'age'])
print(info.values()) # dict_values([33, '男', '冯八一'])
print(info.items()) # dict_items([('age', 33), ('sex', '男'), ('name', '冯八一')])

1.遍历字典的key(键)

info = {'name': '冯八一', 'age': 33, 'sex':'男'}
for key in info.keys():
print(key,end=' ') #name age sex

2.遍历字典的value(值)

info = {'name': '冯八一', 'age': 33, 'sex':'男'}
for value in info.values():
print(value,end=' ') #冯八一 33 男

3.遍历字典的项(元素)

info = {'name': '冯八一', 'age': 33, 'sex':'男'}
for item in info.items():
print(item,end=' ') # ('name', '冯八一') ('age', 33) ('sex', '男')

4.遍历字典的key-value(键值对)

info = {'name': '冯八一', 'age': 33, 'sex':'男'}
for key,value in info.items():
print('key=%s,value=%s' %(key,value))
key = name, value = 冯八一
key = age, value = 33
key = sex, value = 男

posted @ 2024-05-14 18:23  一步一个脚印的amy  阅读(5)  评论(0编辑  收藏  举报