brand=['李宁','耐克','阿迪达斯']
slogan=['一切皆有可能','Just do it','impossible is nothing']
print ('李宁的口号是:',slogan[brand.index('李宁')])
#-->李宁的口号是: 一切皆有可能
键值组合
dict1={'李宁':'一切皆有可能','耐克':'Just do it','阿迪达斯':'impossible is nothing'}
print('李宁的口号是:',dict1['李宁'])
#-->李宁的口号是: 一切皆有可能
#创造一个空的字典
dict2={}
#创造一个字典
dict3={1:"one",2:"two",3:"three"}
dict3[2]#'two'
dict3=dict((('F',70),('i',105),('s',115),('h',104),('C',67)))
>>> dict3#一个映射类型的参数mapping
{'i': 105, 'F': 70, 'h': 104, 'C': 67, 's': 115}
#key+value的形式创建字典,会自动排序,不能使用字符串形式,会自动变成字符串
>>> dict4=dict(小甲鱼='编程改变世界',花花='小甲鱼为什么不加引号')
>>> dict4
{'花花': '小甲鱼为什么不加引号', '小甲鱼': '编程改变世界'}
>>> dict4['花花']='就是这种形式,实际上会自动添加引号'
>>> dict4['草草']='直接给键赋值,存在的就修改,不存在就添加'
>>> dict4
{'草草': '直接给键赋值,存在的就修改,不存在就添加', '花花': '就是这种形式,实际上会自动添加引号', '小甲鱼': '编程改变世界'}
#字典比序列更智能,能添加也能修改
>>> dict1={}
>>> dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
>>> dict1.fromkeys((1,2,3),'number')
{1: 'number', 2: 'number', 3: 'number'}
>>> dict1.fromkeys((1,2,3),('noe','two','three'))
{1: ('noe', 'two', 'three'), 2: ('noe', 'two', 'three'), 3: ('noe', 'two', 'three')}
>>> dict1=dict1.fromkeys(range(5),'赞')
>>> dict1
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞'}
>>> for eachkey in dict1.keys():
print (eachkey)
0
1
2
3
4
>>> for eachvalue in dict1.values():
print (eachvalue)
赞
赞
赞
赞
赞
>>> for eachitem in dict1.items():
print (eachitem)
(0, '赞')
(1, '赞')
(2, '赞')
(3, '赞')
(4, '赞')
>>> print(dict1[4])
赞
>>> print(dict1[5])
'''Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
print(dict1[5])
KeyError: 5
'''
>>> print(dict1.get(5))
None
>>> print(dict1.get(5,'未有'))
未有
>>> print(dict1.get(4,'未有'))
赞
>>> 5 in dict1 #查找的是键不是值
False
>>> 4 in dict1
True
>>> dict1
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞'}
>>> dict1.clear()
>>> dict1
{}
#清空字典用clear(),使用{}并没有将字典删除
>>> a={1:"good"}
>>> b=a
>>> a={}
>>> a
{}
>>> b
{1: 'good'}
>>> a=b
>>> a.clear()
>>> a
{}
>>> b
{}
>>> a={1:"one",2:"two",3:"three"}
>>> b=a.copy()
>>> c=a
>>> a
{1: 'one', 2: 'two', 3: 'three'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> c
{1: 'one', 2: 'two', 3: 'three'}
>>> id(a)
54295368
>>> id(b)
57779848
>>> id(c)
54295368
>>> c[4]='four'
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> a.pop(2)#给定键弹出值
'two'
>>> a
{1: 'one', 3: 'three', 4: 'four'}
>>> a.popitem()#弹出项,popitem可以看做从字典随机弹出一个,因为字典没有序
(1, 'one')
>>> a
{3: 'three', 4: 'four'}
>>> a.setdefault("小白")
>>> a
{3: 'three', 4: 'four', '小白': None}
>>> a.setdefault(5,'five')
'five'
>>> a
{3: 'three', 4: 'four', 5: 'five', '小白': None}
>>> b={"小白":'狗'}
>>> a.update(b)#update用一个字典更新另一个字典
>>> a
{3: 'three', 4: 'four', 5: 'five', '小白': '狗'}
字典
最新推荐文章于 2020-11-06 20:37:57 发布