brand = ['li ning','nike','aididas']
slogan = ['everything is possible','just do it','nothing is impossible']
print('李寧:',slogan[brand.index('li ning')])
無序
映射關係,只有一個映射類型的參數mapping
例一
>>> dirc1 = {'nike':'nothing is impossible','adiads':'just do it'}
>>> print('耐克:',dirc1['nike'])
耐克: nothing is impossible
①用函數dict()創建字典,用列表、括號將其僞裝成一個值
>>> dict3 = dict((('C','cat'),('M','mouse'),('D','dog')))
>>> dict3
{ 'C': 'cat', 'M': 'mouse', 'D': 'dog'}
例三
>>> dict3 = dict([('C','cat'),('M','mouse'),('D','dog')])
>>> dict3
{'C': 'cat', 'M': 'mouse', 'D': 'dog'}
例四
>>> dict4 = dict(C='cat')
>>> dict4
{'C':'cat'}
③dict.fromkeys()
創建一個新的字典(若dict1未命名,則需使用dict.fromkeys)
共有兩個參數,key value(若不提供值,默認爲None)
>>> dict1 = {}
>>> dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
#例七
>>> a = dict.fromkeys((1,2),(9,2))
>>> a
{1: (9, 2), 2: (9, 2)}
>>> b = dict.fromkeys((3,4),'a')
>>> b
{3: 'a', 4: 'a'}
#例八
>>> dict3 = {1: '呵呵', 2: '呵呵', 3: '呵呵'}
>>> dict3.fromkeys(5,'哈哈')
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
dict3.fromkeys(5,'哈哈')
TypeError: 'int' object is not iterable
#例九 (fromkeys創建新字典,原字典不變)
>>> dict3 = {1: '呵呵', 2: '呵呵', 3: '呵呵'}
>>> dict3.fromkeys('5','哈哈')
{'5': '哈哈'}
>>> dict3
{1: '呵呵', 2: '呵呵', 3: '呵呵'}
①dict[key] = value
例
>>> a = {1:'one',2:'two',3:'three'}
>>> a.setdefault(6)
>>> a
{1: 'one', 2: 'two', 3: 'three', 6: None}
>>> a.setdefault(7,'小白')
'小白'
>>> a
{1: 'one', 2: 'two', 3: 'three', 6: None, 7: '小白'}
①keys()
dict1.keys()返回一個可迭代對象
③items()
dict1.items()
④get()
dict1.get(key,TempValue)
>>> 1 in dict1
True
>>> '2' in dict1
False
#在序列中查找的是元素的值,而不是元素的索引號
6.清空字典
dict1.clear()
7.淺拷貝
dict1.copy()
淺拷貝和賦值的區別
>>> a = {1:'one',2:'two',3:'three'}
>>> b = a
>>> c = a.copy()
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> c
{1: 'one', 2: 'two', 3: 'three'}
>>> id(a)
2115434822536
>>> id(b)
2115434822536
>>> id(c)
2115434952024
>>> b[4] = 'four'
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> b
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> c
{1: 'one', 2: 'two', 3: 'three'}
pop給定鍵,彈出對應的值
popitem彈出一個項(隨機)
>>> a = {1:'one',2:'two',3:'three'}
>>> a.pop()
>>> a.pop(3)
'three'
>>> a
{1: 'one', 2: 'two'}
>>> a = {1:'one',2:'two',3:'three'}
>>> a.popitem()
(3, 'three')
>>> a
{1: 'one', 2: 'two'}
9.字典的更新
.update()
#利用字典或映射關係來更新另一個字典
>>> a = {1:'one',2:'two',3:'three'}
>>> b = {'小白':'狗'}
>>> a.update(b)
>>> a
{1: 'one', 2: 'two', 3: 'three', '小白': '狗'}