What are the ways to learn Python's dictionary from 0 to 1 [Lebo TestPro]

The first two issues of the serialization:
Python string detailed knowledge points to explain the attached code [learn Python from 0 to 1]
What is the method of Python list, with the actual case source code

Complementary courses for free:
300-minute Python basic introductory course for free

<1> Viewing elements
In addition to using key to find data, you can also use get to get data
demo:

    info = {
    
    'name':'乐搏学院','age':18}
print(info['name']) # 获取名字
结果:乐搏学院
    # print(info['sex']) # 获取不存在的key,会发生异常
print(info.get('sex')) # 获取不存在的key,获取到空的内容,不会出现异常

<2> Modify elements
The data in each element of the dictionary can be modified, as long as the key is found, the
demo can be modified:

    info = {
    
    'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'}
    newId = input('请输入新的学号')
    info['id'] = int(newId)
print('修改之后的id为%d:'%info['id'])

<3> Add element
demo: access non-existing elements

    info = {
    
    'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}
    print('id为:%d'%info['id'])
如果在使用 变量名['键'] = 数据 时,这个“键”在字典中,不存在,那么就会新增这个元素
demo:添加新的元素
    info = {
    
    'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}

    # print('id为:%d'%info['id'])#程序会终端运行,因为访问了不存在的键

    newId = input('请输入新的学号')

    info['id'] = newId

    print('添加之后的id为:%d'%info['id'])

Result:
Please enter the new student number 188.
The added id is: 188

<4> Delete elements
There are the following types of operations to delete the dictionary:

del
clear()
demo:del删除指定的元素

    info = {
    
    'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}

    print('删除前,%s'%info['name'])

    del info['name']

    print('删除后,%s'%info['name'])
demo:del删除整个字典

    info = {
    
    'name':'monitor', 'sex':'f', 'address':'China'}

    print('删除前,%s'%info)

    del info

    print('删除后,%s'%info)

demo:clear清空整个字典

    info = {
    
    'name':'monitor', 'sex':'f', 'address':'China'}

    print('清空前,%s'%info)

    info.clear()

    print('清空后,%s'%info)

Guess you like

Origin blog.csdn.net/leboxy/article/details/110430828