• python进阶(4)--字典


    文档目录:

    一、一个简单的字典
    二、字典-增删改
    三、遍历字典
    四、字典嵌套

    ---------------------------------------分割线:正文--------------------------------------------------------

    一、一个简单的字典

    alien_0={'color':'green','point':5}
    print(type(alien_0))

    查看结果:

    <class 'dict'>

     

    二、字典-增删改

    1、访问字典

    alien_0={'color':'green','point':5}
    print(alien_0['color'])
    print(alien_0.get('point'))

    查看结果

    green
    5

    2、更新字典

    alien_0={'color':'green','point':5}
    alien_0['x_postion']=0
    alien_0['y_postion']=25
    alien_0['color']='yellow'
    print(alien_0)

    查看结果:

    {'color': 'yellow', 'point': 5, 'x_postion': 0, 'y_postion': 25}

    3、删除键值对

    alien_0={'color':'green','point':5}
    del alien_0['color']
    print(alien_0)

    查看结果:

    {'point': 5}

     

    三、遍历字典

     1、遍历字典的键值对

    alien_0={'color':'green','point':5}
    for a,b in alien_0.items():
        print(f"key:{a}")
        print(f"value:{b}")

    查看结果:

    key:color
    value:green
    key:point
    value:5

    2、遍历字典的所有键

    alien_0={'color':'green','point':5}
    for a in alien_0.keys():
        print(f"key:{a}")

    查看结果:

    key:color
    key:point

    3、遍历字典的所有值

    alien_0={'color':'green','point':5}
    for a in alien_0.values():
        print(f"value:{a}")

    查看结果:

    value:green
    value:5

    4、遍历并去重字典的值

    alien_0={'test01':1,'test02':1,'test03':2,'test04':2,'test05':3,'test06':3,}
    for a in set(alien_0.values()):
        print(f"key:{a}")

    查看结果:

    key:1
    key:2
    key:3

    四、字典嵌套

    1、列表套字典

    alien_0={'color':'green','point':5}
    alien_1={'color':'yellow','point':10}
    list1=[alien_0,alien_1]
    print(list1)
    for alien in list1:
        print(alien)

    查看结果:

    [{'color': 'green', 'point': 5}, {'color': 'yellow', 'point': 10}]
    {'color': 'green', 'point': 5}
    {'color': 'yellow', 'point': 10}

    2、字典套列表

    testList=['myok1','myok2']
    testDict={'task1':'mydict','task2':testList}
    print(testDict)
    for list1 in testDict['task2']:
        print(list1)

    查看结果:

    {'task1': 'mydict', 'task2': ['myok1', 'myok2']}
    myok1
    myok2

    3、字典套字典

    alien_0={'color':'green','point':5}
    alien_1={'color':'yellow','point':10}
    aliens={'fisrt':alien_0,'second':alien_1}
    print(aliens)
    for a,b in aliens['second'].items():
        print(f"{a}:{b}")

    查看结果:

    {'fisrt': {'color': 'green', 'point': 5}, 'second': {'color': 'yellow', 'point': 10}}
    color:yellow
    point:10
  • 相关阅读:
    format的用法

    TADOQuery池
    10分钟了解JSON Web令牌(JWT)
    PHP操作Redis数据库常用方法
    平时在PHP编码时有没有注意到这些问题
    利用 Composer 一步一步构建自己的 PHP 框架(四)——使用 ORM
    ORM的详解
    oracle NLS_LANG环境变量设置
    验证选择每日学习总结:DropDownList是否已选择验证、存储过程参数为sql字符串问题、将截断字符串或二进制数据。\r\n语句已终止
  • 原文地址:https://www.cnblogs.com/mrwhite2020/p/14665202.html
Copyright © 2020-2023  润新知