字典类型的内置方法(dict)
1.用途
存多个值,但每一个值都有一个key与之对应,key对值有描述功能;多用于存的值表示的是不同的状态时,例如存的值有姓名、年龄、身高、体重、爱好。
2.定义
在{}里用逗号隔开多个元素,没个元素都是以键值对的形式存储的:value可以是任意数据类型,而key通常应该是字符串类型,但是key必须为不可变类型
3.常用操作+内置方法
**优先掌握**
1.按key存取值:可存可取
2.长度len
3.成员运算in/not in
4.删除del
5.键keys()、值values()、键值对items()
6.循环
1.按key存取值:可存可取
age_dict = {'nick':18,'egon':19,'rocky':20}
print(age_dict['nick'])
# 18
age_dict['alex'] = 21
print(age_dict)
# {'nick': 18, 'egon': 19, 'rocky': 20, 'alex': 21}
2.长度len
age_dict = {'nick':18,'egon':19,'rocky':20}
print(len(age_dict))
# 3
3.成员运算in和not in
age_dict = {'nick':18,'egon':19,'rocky':20}
print('alex' in age_dict)
# False
4.删除
age_dict = {'nick':18,'egon':19,'rocky':20}
del age_dict['nick']
print(age_dict)
# {'egon': 19, 'rocky': 20}
5.键keys()、值values()、键值对items()
age_dict = {'nick':18,'egon':19,'rocky':20}
print(age_dict.keys())
# dict_keys['nick', 'egon', 'rocky'])
print(age_dict.values())
# dict_values([18, 19, 20])
print(age_dict.items())
# dict_items([('nick', 18), ('egon', 19), ('rocky', 20)])
6.循环
age_dict = {'nick':18,'egon':19,'rocky':20}
for k , v in age_dict.items():
print(k,v)
## 结果
nick 18
egon 19
rocky 20
**需要掌握**
1.get
2.update
3.fromkeys
4.setdefault
1.get()
age_dict = {'nick':18,'egon':19,'rocky':20}
print(age_dict.get('nick'))
# 18
2.update()
age_dict = {'nick':18,'egon':19,'rocky':20}
age-dict2 = {'alex':21}
age_dict.update(age-dict2)
print(age_dict)
# {'nick': 18, 'egon': 19, 'rocky': 20, 'alex': 21}
3.fromkeys()
age_dic = dict.fromkeys(['nick', 'egon', 'rocky'], 18)
print(age_dic)
# {'nick': 18, 'egon': 18, 'rocky': 18}
4.setdefault()
在字典里查找某一个key的值,如果有这个key就返回它的值,字典里的元素不会发生变化:如果查找的元素字典没有,我们可以自己定义这个元素的值,并且也会返回我们定义的这个值,但是字典里元素会自动的添加这个键值对
age_dict = {'nick':18,'egon':19,'rocky':20}
print(age_dict.setdefault('nick',19))
# 18
print(age_dict)
# {'nick': 18, 'egon': 19, 'rocky': 20}
print(age_dict.setdefault('alex',20))
# 20
print(age_dict)
# {'nick': 18, 'egon': 19, 'rocky': 20, 'alex': 20}