day5 字典的基本操作
Posted feige6
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了day5 字典的基本操作相关的知识,希望对你有一定的参考价值。
字典:
字典的基本概念:
字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的。可哈希表示key必须是不可变类型,如:数字、字符串、元组。
字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过索引存取
1增:
dict = {‘name‘: ‘wangjifei‘,‘age‘:27,‘hometown‘:‘xingtai‘} dict[‘job‘] = ‘IT‘#有就覆盖,没有就添加 print(dict)#{‘name‘: ‘wangjifei‘, ‘age‘: 27, ‘hometown‘: ‘xingtai‘, ‘job‘: ‘IT‘} #setdefault 在字典中添加键值对,如果只有键那对应的值是none,但是如果原字典中存在设置的键值对,则他不会更改或者覆盖。 dict.setdefault(‘hometown‘,‘xingtai‘) print(dict)#{‘name‘: ‘wangjifei‘, ‘age‘: 27, ‘hometown‘: ‘xingtai‘, ‘job‘: ‘IT‘} dict.setdefault(‘name‘,‘gaoliang‘) print(dict)#{‘name‘: ‘wangjifei‘, ‘age‘: 27, ‘hometown‘: ‘xingtai‘, ‘job‘: ‘IT‘}
2、删
dict = {‘name‘: ‘wangjifei‘,‘age‘:27,‘hometown‘:‘xingtai‘} s = dict.pop(‘age‘)#返回删除的value s2 = dict.pop(‘hobby‘,‘没有返回no‘)#若删除的键不存在,可以返回添加的任何信息,没有信息就报错 print(dict) print(s) print(s2)
dict = {‘name‘: ‘wangjifei‘,‘age‘:27,‘hometown‘:‘xingtai‘} s1 = dict.popitem()# 随机删除字典中的某个键值对,将删除的键值对以元祖的形式返回 print(s1)#(‘hometown‘, ‘xingtai‘) print(dict)#{‘name‘: ‘wangjifei‘, ‘age‘: 27} del dict[‘name‘]#无返回值 del dict#删除整个字典
3、改:
dict = {‘name‘: ‘wangjifei‘,‘age‘:27,‘hometown‘:‘xingtai‘} dic = {‘name‘:‘gaoliang‘,‘hobby‘:‘girl‘} dict[‘name‘] = ‘gaoliang‘#有则覆盖没有就添加 print(dict)#{‘name‘: ‘gaoliang‘, ‘age‘: 27, ‘hometown‘: ‘xingtai‘} dic = {‘name‘:‘gaoliang‘,‘hobby‘:‘girl‘} dict.update(dic)#两个字典的更新,将dic里面的所有键值对,覆盖添加到dict中,dic不变 print(dict)#{‘name‘: ‘gaoliang‘, ‘age‘: 27, ‘hometown‘: ‘xingtai‘, ‘hobby‘: ‘girl‘} print(dic)#{‘name‘: ‘gaoliang‘, ‘hobby‘: ‘girl‘}
4、查:
dict = {‘name‘: ‘wangjifei‘,‘age‘:27,‘hometown‘:‘xingtai‘} print(dict[‘name‘])#wangjifei#key值查找 print(dict.get(‘age‘))#27 #内置函数查找,找到返回value。没有key就返回None print(dict.get(‘hobby‘,‘没有此键‘))#没有此键 #key在字典里就返回对应的value,没有就返回添加的内容,没有添加内容就返回None
dict = {‘name‘: ‘wangjifei‘,‘age‘:27,‘hometown‘:‘xingtai‘} print(dict.keys(),type(dict.keys())) print(dict.values(),type(dict.values())) print(dict.items(),type(dict.items()))
》》》
dict_keys([‘name‘, ‘age‘, ‘hometown‘]) <class ‘dict_keys‘>
dict_values([‘wangjifei‘, 27, ‘xingtai‘]) <class ‘dict_values‘>
dict_items([(‘name‘, ‘wangjifei‘), (‘age‘, 27), (‘hometown‘, ‘xingtai‘)]) <class ‘dict_items‘>
for循环遍历查找字典:
第一种:
dict = {‘name‘: ‘wangjifei‘,‘age‘:27,‘hometown‘:‘xingtai‘} for i,v in dict.items(): print(i,v)
》》》
name wangjifei
age 27
hometown xingtai
第二种:
dict = {‘name‘: ‘wangjifei‘,‘age‘:27,‘hometown‘:‘xingtai‘} for i in dict: print(i,dict[i])
》》》
name wangjifei
age 27
hometown xingtai
分别赋值法:
a,b = 1,3 print(‘a‘,a) print(‘b‘,b)
a,b = b, a print(‘a‘,a) print(‘b‘,b)
》》》
a 1
b 3
a 3
b 1
以上是关于day5 字典的基本操作的主要内容,如果未能解决你的问题,请参考以下文章