python 第五天学习笔记
今天学习第七章 字典和集合
dict2 = {"a":"one","b":"two","c":"three"}
dict2["b"]
结果是“two”
定义字典用{}
定义空字典 empty={}
这三种方法得到的结果一样:
dict1 = {"F":70,"i":105,"s":115,"h":104,"C":67} 字典的原始定义方法{}
dict2 = dict((("F",70),("i",105),("s",115),("h",104),("C",67))) 打包成一个元组序列
dict3 = dict(F=70,i=105,s=115,h=104,C=67) 具有映射关系,字符串不用加引号
结果为:{'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67}
给字典赋值或者改写字典的值:
dict1["x"]=20 用中括号
用多种方法创建字典:
dict1 = {"one":1,"two":2,"three":3} 最原始方法
dict2=dict(one=1,two=2,three=3) 映射方法
dict3 = dict(zip(["one","two","three"],[1,2,3])) zip方法
dict4 = dict([("one",1),("two",2),("three",3)]) 【】为打包成一个tuple元组
dict5 = dict((("one",1),("two",2),("three",3))) ()为打包成一个list列表
dict6 = dict({"one":1,"two":2,"three":3}) {} 为打包成一个字典dict
注意:命名的时候千万不要命名成dict,后续调用dict时全部调用成命名的那个了
各种内置方法:
fromkeys ((),()) 创建并返回一个新的字典,有两个参数,第一个是键,第二个是值
基本用法:
dict1 = {}
dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
dict1.fromkeys((1,2,3),"a") 第二个参数返回所有的值
{1: 'a', 2: 'a', 3: 'a'}
dict1.fromkeys((1,2,3),("a","b","c"))
{1: ('a', 'b', 'c'), 2: ('a', 'b', 'c'), 3: ('a', 'b', 'c')} 第二个参数不是分别的对应返回
keys 键
values 值
items 键值对应项
dict1 = dict1.fromkeys(range(10),"赞")
>>> dict1
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞', 8: '赞', 9: '赞'}
dict1.keys()
dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
dict1.values()
dict_values(['赞', '赞', '赞', '赞', '赞', '赞', '赞', '赞', '赞', '赞'])
dict1.items()
dict_items([(0, '赞'), (1, '赞'), (2, '赞'), (3, '赞'), (4, '赞'), (5, '赞'), (6, '赞'), (7, '赞'), (8, '赞'), (9, '赞')])
查看某一项
print(dict1[10]) #查看第10项
Traceback (most recent call last):
File "<pyshell#88>", line 1, in <module>
print(dict1[10])
KeyError: 10 #找不到会报错
>>> dict1.get(10) #用get找不到会返回None,啥都没有
>>> dict1.get(9)
'赞'
get可以不存在的键赋值:
>>> dict1.get(10,"a") 最终也不会改变dict1,dict1里面没有10项
'a'
>>> dict1.get(9,"a") 但是不能给已经存在的键赋值
'赞'
想知道某一个键在不在字典中,用in 和 not in
9 in dict1
True
setdefault 设置默认值 用法和get类似,但是用setdefault()在字典中找不到对应的键时,会自动添加None
>>> a.setdefault(3)
'three'>>> a.setdefault(5)
>>> a
{1: 'one', 2: 'two', 3: 'three', 5: None}
清空一个字典用clear()
dict1.clear()
复制字典用copy()
b = a.copy()
pop 突然弹出来,给定键弹出对应的值 ,并且弹出即删除
popitem 随机弹出一个项,在字典中是没有顺序的
>>> a={1: 'one', 2: 'two', 3: 'three'}
>>> a
{1: 'one', 2: 'two', 3: 'three'}
>>> a.pop(1) #用pop弹出键为1对应的数
'one'
>>> a #此时的a弹出的数已经移除
{2: 'two', 3: 'three'}
>>> a.popitem() #用popitem随机弹出一对项
(3, 'three')
>>> a #此时的a弹出的项也被移除
{2: 'two'}
>>> a.popitem()
(2, 'two')
>>> a #最后,a为空字典
{}
update() 更新
>>> a.update({5:"five"})
>>> a
{1: 'one', 2: 'two', 3: 'three', 5: 'five'}
总结这次所学:
fromkeys
keys
values
items
get
in not in
setdefault
clear
pop
popitem
update
下次看77页,第28个视频。