栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Python】字典

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Python】字典

一、增加、修改
  • 语法:字典序列[key] = 值
注意:如果key存在则修改这个key对应的值;如果key不存在则新增此键值对。
dict = {'name' : 'Tom', 'age':20, 'gender' : '男'}
dict['name'] = 'Rose'
print(dict)
#{'name': 'Rose', 'age': 20, 'gender': '男'}

dict['id'] = 110
print(dict)
#{'name': 'Rose', 'age': 20, 'gender': '男', 'id': 110}

二、修改
  • del()/del:删除字典或删除字典中指定键值对。
语法:1.del(字典序列) : 删除整个字典。            2.del 字典序列[key] : 删除指定key对应的值。
dict = {'name' : 'Tom', 'age':20, 'gender' : '男'}
del dict['name']
print(dict)
#{'age': 20, 'gender': '男'}

del(dict)
print(dict)
#dict已被删除
  •  clear():清空字典。
语法:字典序列.clear()
dict.clear()
print(dict)
#{}

三、查找
  • 语法:字典序列[key]
dict = {'name' : 'Tom', 'age':20, 'gender' : '男'}
print(dict['name']) #Tom
print(dict[id])#报错
  • get():如果当前查找的key不存在则返回第二个参数(默认值),如果             省略第二个参数,则返回None。
语法:字典序列.get(key, 默认值)
dict = {'name' : 'Tom', 'age':20, 'gender' : '男'}
print(dict.get('name'))#Tom
print(dict.get('id', 110))#110
print(dict.get('id'))#None
  •  keys():返回字典中的key。
语法:字典序列.keys()
dict = {'name' : 'Tom', 'age':20, 'gender' : '男'}
print(dict.keys())
#dict_keys(['name', 'age', 'gender'])
  • values():返回字典中key对应的值。
语法:字典序列.values()
dict = {'name' : 'Tom', 'age':20, 'gender' : '男'}
print(dict.values())
dict_values(['Tom', 20, '男'])
  • items():放回字典中的key和key所对应的值。
语法:字典序列.items()
dict = {'name' : 'Tom', 'age':20, 'gender' : '男'}
print(dict.items())
#dict_items([('name', 'Tom'), ('age', 20), ('gender', '男')])

四、遍历 1、遍历字典的key
dict = {'name' : 'Tom', 'age':20, 'gender' : '男'}
for key in dict.keys():
    print(key)
2、遍历字典的value
dict = {'name' : 'Tom', 'age':20, 'gender' : '男'}
for value in dict.values():
    print(value)
3、遍历字典的元素
dict = {'name' : 'Tom', 'age':20, 'gender' : '男'}
for item in dict.items():
    print(item)
4、遍历字典的键值对
dict = {'name' : 'Tom', 'age':20, 'gender' : '男'}
for key, value  in dict.items():
    print(f'{key} = {value}')

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/308664.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号