Python 字典
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
键必须是唯一的,但值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
字典的创建方法:
方法一:
dict1={"1":'one',"2":'two',"3":'there',"4":'four'}
方法二
dict2=dict(([1,'one'],[2,'two'],[3,'there'],[4,'four']))
方法三
dict3=dict(一='one',二='two',三='there',四='four')
注意方法三的左侧不能加引号或数字否则变成赋值报错
字典的初始化(fromkeys)方法:
描述
Python 字典 fromkeys() 函数用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。
语法
fromkeys()方法语法:
dict.fromkeys(seq[, value])
参数
- seq -- 字典键值列表。
- value -- 可选参数, 设置键序列(seq)的值。
返回值
该方法返回列表。
实例
value默认为none
dict1={}
dict1.fromkeys((1,2,3,4))
#初始化结果{1: None, 2: None, 3: None, 4: None}
整个字典初始化赋值dict1.fromkeys((1,2,3,4),"defualt") #结果{1: 'defualt', 2: 'defualt', 3: 'defualt', 4: 'defualt'}
字典按键查找
dict1={1:"one",2:"two",3:"there",4:"four"}
dict1[1]
#返回值'one'
keys(),values(),items()方法分别来遍历所有键,值,项目
dict1={1:"one",2:"two",3:"there",4:"four"}
for eachkey in dict1.keys():
print(eachkey)
'''
返回结果
1
2
3
4
'''
for EachValue in dict1.values():
print(EachValue)
one
two
there
four
for EachItems in dict1.items():
print(EachItems)
(1, 'one')
(2, 'two')
(3, 'there')
(4, 'four')
判断项目是否存在
get()方法
dict1.get(5,"不存在")
'不存在'
dict1.get(4,"不存在")
'four'
in判断
5 in dict1
False
4 in dict1
True
字典删除
POP()删除指定值键
dict1={1:"one",2:"two",3:"there",4:"four"}
dict1.pop(2)
'two'
dict1
{1: 'one', 3: 'there', 4: 'four'}
popitem()随即删除项目(一般为末尾对)
dict1={1:"one",2:"two",3:"there",4:"four"}
dict1.popitem()
(4, 'four')
dict1
{1: 'one', 2: 'two', 3: 'there'}
clear()方法删除整个字典dict1={1:"one",2:"two",3:"there",4:"four"}
>>> dict1.clear()
>>> dict1
{}
字典添加项目
setdefault()
dict1.setdefault(5,"five")
'five'
dict1
{1: 'one', 2: 'two', 3: 'there', 4: 'four', 5: 'five'}
update()
dict1
{1: 'one', 2: 'two', 3: 'there', 4: 'four', 5: 'five'}
dict2={6:"six"}
dict1.update(dict2)
dict1
{1: 'one', 2: 'two', 3: 'there', 4: 'four', 5: 'five', 6: 'six'}