python basics - dictionary

Dictionary introduction

Think about it:

if there is a list

     nameList = ['xiaoZhang', 'xiaoWang', 'xiaoLi'];

It is necessary to spell the name "xiaoWang" wrong, and modify it through the code:

     nameList[1] = 'xiaoxiaoWang'

If the order of the list has changed, as follows

     nameList = ['xiaoWang', 'xiaoZhang',  'xiaoLi'];

At this point, you need to modify the subscript to complete the modification of the name.

     nameList[0] = 'xiaoxiaoWang'

有没有方法,既能存储多个数据,还能在访问元素的很方便就能够定位到需要的那个元素呢?

answer:

dictionary

Another scene:

Student information list, each student information includes student number, name, age, etc. How to find the information of a certain student?

>>> studens = [[1001, "王宝强", 24], [1002, "马蓉", 23], [1005, "宋喆",24], ...] 

Loop through? No!

 

<2> Dictionary in software development

The variable info is of dictionary type:

info = { ' name ' : ' Monitor ' , ' id ' : 100, ' sex ' : ' f ' , ' address ' : ' Earth Asia China Beijing ' }

 

illustrate:

  • Dictionaries, like lists, can also store multiple pieces of data
  • When finding an element in a list, it is based on the subscript
  • When looking for an element in the dictionary, it is based on the 'name' (that is, the value in front of the colon: such as 'name', 'id', 'sex' in the above code)
  • Each element of the dictionary consists of 2 parts, key:value. For example 'name': 'squad leader', 'name' is the key, and 'squad leader' is the value

<3> Access the value according to the key

   info = { ' name ' : ' Monitor ' , ' id ' : 100, ' sex ' : ' f ' , ' address ' : ' Earth Asia China Beijing ' }

    print(info['name'])
    print(info['address'])

 

result:

    班长
    地球亚洲中国北京

If you access a non-existent key, you will get an error:

>>> info['age']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module> KeyError: 'age' 

 

When we are not sure if a key exists in the dictionary and want to get its value, we can use the get method, and we can also set a default value:

>>> age = info.get('age')
>>> age #'age'键不存在,所以age为None
>>> type(age) <type 'NoneType'> >>> age = info.get('age', 18) # 若info中不存在'age'这个键,就返回默认值18 >>> age 18

Common operations on dictionaries

<1> Modify elements

The data in each element of the dictionary can be modified, as long as it is found through the key, it can be modified

demo:

info = { ' name ' : ' Monitor ' , ' id ' : 100, ' sex ' : ' f ' , ' address ' : ' Earth Asia China Beijing ' }
newId = input( ' Please enter a new student ID ' )
info[ ' id ' ] = int(newId)
 print ( ' The modified id is %d: ' %info[ ' id ' ])

Results of the:

 

<2>Add elements

demo:

info = { ' name ' : ' Monitor ' , ' sex ' : ' f ' , ' address ' : ' Earth Asia China Beijing ' }
 # print('id is:%d'%info['id'])#Program The terminal will run because the non-existent key 
newId = input( ' please enter a new student ID ' ) is accessed
info[ ' id ' ] = newId
 print ( ' The id after adding is: %s ' %info[ ' id ' ])

Results of the:

 

<3> Delete elements

There are several ways to delete a dictionary:

  • the
  • clear()

demo:del deletes the specified element

info = { ' name ' : ' Monitor ' , ' sex ' : ' f ' , ' address ' : ' Earth Asia China Beijing ' }

print ( ' Before delete, %s ' %info[ ' name ' ])
 del info[ ' name ' ]

print ( ' After deleting, %s ' %info[ ' name ' ])

Results of the:



demo:del删除整个字典
info = { ' name ' : ' Monitor ' , ' sex ' : ' f ' , ' address ' : ' Earth Asia China Beijing ' }

print ( ' Before deleting, %s ' % info)
 del info

print ( ' After deleting, %s ' %info)

Results of the:

 

 

<4>len()

Measure the number of key-value pairs in the dictionary

info = { ' name ' : ' Monitor ' , ' sex ' : ' f ' , ' address ' : ' Earth Asia China Beijing ' }
result = len(info)
 print ( ' Number of key-value pairs: ,%d ' %result)

Results of the:

 

<5>keys

Returns a list containing all the keys of the dictionary

info = { ' name ' : ' Monitor ' , ' sex ' : ' f ' , ' address ' : ' Earth Asia China Beijing ' }
result=info.keys()
print('键,%s'%result)

 

<6>values

Returns a list containing all the values ​​of the dictionary

info = { ' name ' : ' Monitor ' , ' sex ' : ' f ' , ' address ' : ' Earth Asia China Beijing ' }
result=info.values()
print('值,%s'%result)

 

<7>items

Returns a list containing all (key, value) tuples

info = { ' name ' : ' Monitor ' , ' sex ' : ' f ' , ' address ' : ' Earth Asia China Beijing ' }
result=info.items()
print('%s'%result)



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325207364&siteId=291194637