python 字典

来源:互联网 发布:手机如何切换软件 编辑:程序博客网 时间:2024/06/09 15:29

1.什么是字典

字典是python内置函数,有key-value存储,跟java中map同理,字典有{key:value}组成

score = {'语文':98,'数学':100,'英语':60,'编程':90}print(score['数学'])

字典中key与value方法

score = {'语文':98,'数学':100,'英语':60,'编程':90}print(score.keys())#dict_keys(['语文', '数学', '英语', '编程'])for key in score.keys():    print(key)# 语文# 数学# 英语# 编程print(score.values())#dict_values([98, 100, 60, 90])for value in score.values():    print(value)# 98# 100# 60# 90

2.创建字典

通过关键字创建字典

dict1 = dict(语文=98,数学=100,英语=60)print(dict1['语文'])

元组创建字典

dict2 = dict((("语文",98),("数学",100),('英语',60)))print(dict2['数学'])

fromkeys

dict3={}dict3=dict3.fromkeys(('语文','数学','英语'),98)==============>dict3=dict.fromkeys(('语文','数学','英语'),98)print(dict3)--------------{'语文': 98, '数学': 98, '英语': 98}

3.取字典元素get()

score = {'语文':98,'数学':100,'英语':60,'编程':90}print(score.get('数学'))#100print(score.get('体育','字典里没有体育'))#如果字典没有打印后面提示:字典里没有体育

4.给字典添加元素setdefault()和更新字典元素update()

score = {'语文':98,'数学':100,'英语':60}score.setdefault('java',100)print(score) # {'语文': 98, '数学': 100, '英语': 60, 'java': 100}a = {'英语':88}score.update(a) print(score) # {'语文': 98, '数学': 100, '英语': 88, 'java': 100}

5.判断字典里有无某个元素 in

score = {'语文':98,'数学':100,'英语':60,'编程':90}print('体育' in score) # Falseprint('数学' in score) # True

6.浅拷贝 copy()

在改变 语文 成绩时,由于a是浅拷贝,所以a的字典不会改变

score = {'语文':98,'数学':100,'英语':60,'编程':90}a = score.copy()b = scoreprint(a) # {'语文': 98, '数学': 100, '英语': 60, '编程': 90}print(b) # {'语文': 98, '数学': 100, '英语': 60, '编程': 90}score['语文'] = 30print(a) # {'语文': 98, '数学': 100, '英语': 60, '编程': 90}print(b) # {'语文': 30, '数学': 100, '英语': 60, '编程': 90}

7.删除 pop()

score = {'语文':98,'数学':100,'英语':60,'编程':90}score.pop('英语')print(score) # {'语文': 98, '数学': 100, '编程': 90}

8.清空字典 clear()

score = {'语文':98,'数学':100,'英语':60,'编程':90}score.clear()print(score) # {}