dictionary
A dictionary is an unordered data structure that maps keys to values. The value can be any value (list, function, string, anything). The key must be immutable, for example, a number, string, or tuple .
Dictionary: The word we look up is the key, and the definition we look up is the value.
What is a tuple? (The next article will talk about it in detail)
Python tuples are similar to lists, except that the elements of tuples cannot be modified.
Use parentheses for tuples and square brackets for lists.
Tuple creation is very simple, just add elements in parentheses and separate them with commas.
One, access the value of the dictionary
dir={
'1':'A','2':'B','3':'C','4':'D','5':'I love you'}
print(dir)
print(dir['1'])
print(dir['5'])
Result:
Second, update the dictionary
dir={
'1':'A','2':'B','3':'C','4':'D','5':'I love you'}
print(dir)
dir['6']='I hate you'#增加
print(dir)
dir.update({
'1':'aaa'})#修改
print(dir)
dir.update({
'2':'bbb','7':'I like you'})#同时修改和增加也可以
print(dir)
result:
dir={
'1':'A','2':'B','3':'C','4':'D','5':'I love you'}
print(dir)
del dir['1']#删掉某个key
print(dir)
result:
Not everything can be used as a key
dir={
'1':'A','2':'B','3':'C','4':'D','5':'I love you'}
dir[['aaaaa']]
print(dir)
Error:
3. Use the get() method to return the value of a given key. If you
write this way, you will get an error because there is no run key.
storyCount = {
'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}
print(storyCount['run'])
The result is an error:
But if you write:
storyCount = {
'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}
print(storyCount.get('run',0))#这个0是你自己定义的如果不存在范围的默认的值
print(storyCount.get('run'))#如果你没有设置的话,默认是none
Result:
Four, delete the key, but at the same time can return value
storyCount = {
'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}
count=storyCount.pop('is')
print(count)
print(storyCount)
Results:
Five, traverse the dictionary
storyCount = {
'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}
print(storyCount.keys())#所有key
print(storyCount.values())#所有value
print('-------------------------')
for key in storyCount:
print(key)
print("-------------------------")
for value in storyCount.items():#注意我试了一下这里没有items()不行
print(value)
print("-------------------------")
for key,value in storyCount.items():#注意我试了一下这里没有items()不行
print(key,value)
result: