zoukankan      html  css  js  c++  java
  • 字典简介

    字典

    在本节中,你将学习存储字典的列表、存储列表的字典和存储字典的字典

    6.1  一个简单的字典

    alien_0 = {'alien': 'green', 'points': 5}
    print(alien_0['alien'])
    print(alien_0['points'])
    print(alien_0)
    ========
    output:
    green
    5
    {'alien': 'green', 'points': 5}

    6.2 使用字典

    在python中,字典是一系列键-值对,每个键都与一个值相关联,使用键来访问与之相关联的值,

    与键相关联的值可以是数字,字符串, 列表乃至字典,

    6.3 添加键-值对

    字典是一种动态结构,可随时在其中添加键-值对,

    可依次指定字典名,用方括号括起的键和相关联的值

    eg:

    alien_0 = {'alien': 'green', 'points': 5}
    print(alien_0)
    alien_0['x_position'] = 0
    alien_0['y_position'] = 25
    print(alien_0)
    ==============
    output:
    {'alien': 'green', 'points': 5}
    {'alien': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

    注意:键-值对的排列顺序与添加顺序不同,python不关心键-值对的添加顺序,

    只关心键和值之间的关联关系

     

    6.4 创建一个空字典

    eg:

    alien_0 = {}

    alien_0['color'] = 'green'

    alien_0['points'] = 5

    print(alien_0)

    =============

    output:

    {'color': 'green', 'point': 5}

    使用字典来存储用户提供的数据或在编写能自动生成大量键-值对的代码时,
    通常都需要先定义一个空字典

    6.5 修改字典的值
    eg:
    alien_0 = {}

    alien_0['color'] = 'green'
    alien_0['point'] = 5
    print(alien_0)
    alien_0['point'] = 9
    print(alien_0)

    =========================
    output:
    {'color': 'green', 'point': 5}
    {'color': 'green', 'point': 9}

    =========================

    6.5 删除键-值对

    使用del语句,指定字典名和要删除的键

    eg:

    alien = {'color': 'green', 'point': 5}

    del alien['point']
    print(alien)

    ==============
    output:
    {'color': 'green'}

    6.6 遍历字典
    遍历字典的方式:遍历字典的键-值对,键或值

    遍历所有的键-值对
    eg:
    user_0 = {
        'username': 'efermi',
        'first': 'enric',
        'last': 'fermi'
        }

    for key, value in user_0.items():
        print(" Key:" + key)
        print(" Value:" + value)
    ==========
    output:

    Key:username

    Value:efermi

    Key:first

    Value:enric

    Key:last

    Value:fermi

    ===================

    注意:键-值对的返回顺序与存储顺序不同,

    python不关心键-值对的存储顺序,而只跟踪键和值之间的关联

    6.7 遍历字典中的所有键

    方法keys()

    eg:

    user_0 = {
        'username': 'efermi',
        'first': 'enric',
        'last': 'fermi'
        }

    for key in user_0.keys():
        print(key.title())

    ==================
    output:
    Username
    First
    Last

    ================

    遍历字典时,会默认遍历所有的键

    so, for key in user_0: 输出不会改变

    方法keys() 并非只能用于遍历,它返回一个列表,其中包含字典中的所有键

    6.8 按顺序遍历字典中的所有键

    要以特定的顺序返回元素,可以使用函数sorted()来获得特定顺序排列的键列表的副本

    eg:

    user_0 = {
        'username': 'efermi',
        'first': 'enric',
        'last': 'fermi'
        }

    for key in sorted(user_0.keys()):
        print(key.title())
    =================
    output:
    First
    Last
    Username

    =================

    6.9 遍历字典中的所有值

    使用方法values() 返回值列表,而不包含任何键

    user_0 = {
        'username': 'efermi',
        'first': 'enric',
        'last': 'fermi'
        }

    for value in sorted(user_0.values()):
        print(value.title())

    ====================
    output:
    Efermi
    Enric
    Fermi

    ==============

    这种做法提取字典中所有的值,而没有考虑是否重复,
    最终的列表可能包含大量的重复项,为了剔除重复项,

    可使用集合(set),集合类似于列表,但是元素都是唯一的

    eg:

    languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
    print("*************")
    for language in set(languages.values()):
    print(language.title())
    ----------------------------------------
    output:
    Ruby
    C
    Python

    随着更深入的学习,会有更多的内置功能

    嵌套
    有时候,需要将字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套
    甚至可以字典中嵌套字典

    6.10 字典列表
    eg:
    alien_0 = {'color': 'green', 'points': 5}
    alien_1 = {'color': 'red', 'points': 9}
    alien_2 = {'color': 'black', 'points': 10}

    aliens = [alien_0, alien_1, alien_2]

    for alien in aliens:
    print(alien)
    ------------------------
    output:
    {'color': 'green', 'points': 5}
    {'color': 'red', 'points': 9}
    {'color': 'black', 'points': 10}
    这个案例将字典都放在列表中,最后遍历

    更符合现实的情况是字典不止有三个
    我们使用range()创建30个字典
    eg:
    aliens = []

    for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)

    #display aliens of 5
    for alien in aliens[:5]:
    print(alien)
    print("......")

    #display create how many alien
    print("Total number of aliens: " + str(len(aliens)))


    ------------------------
    output:
    {'color': 'green', 'points': 5, 'speed': 'slow'}
    {'color': 'green', 'points': 5, 'speed': 'slow'}
    {'color': 'green', 'points': 5, 'speed': 'slow'}
    {'color': 'green', 'points': 5, 'speed': 'slow'}
    {'color': 'green', 'points': 5, 'speed': 'slow'}

    如果要修改某一段的数据只需要修改相关的切片即可

    6.11 在字典中存储列表
    将列表存储在字典中
    eg:
    pizza = {
    'crust': 'thick',
    'toppings':['mushrooms', 'extra cheese'],
    }

    for topping in pizza['toppings']:
    print(" " + topping)

    --------------------------------------
    output:
        mushrooms
        extra cheese
    ---------------------------------------
    6.11 在字典中存储字典
    可在字典中嵌套字典,eg:如果有多个网站用户,每个都有独特的用户名
    可在字典中将用户名作为键,然后将每位用户的信息存储在一个字典中,
    并将该字典作为与用户名相关联的值,
    eg:
    users = {
    'aeinstein': {
    'first': 'albert',
    'last': 'einstein',
    'location': 'princeton',
    },
    'mcurie': {
    'first': 'marie',
    'last': 'curie',
    'location': 'paris',
    },
    }


    for user_name, user_info in users.items():
    print(user_name)
    print("full_time " + user_info['first'] + user_info['last'])
    print(user_info['location'])
    ----------------------------------------------
    output:
    aeinstein
    full_time alberteinstein
    princeton
    mcurie
    full_time mariecurie
    paris
    ---------------------------------------------------
    attention: 每位用户的字典结构都相同,这样嵌套的字典处理方便

    总结:
    本节学习:如何定义字典,以及如何使用存储在字典中的信息,
         访问和修改字典中的元素,遍历字典中的所有信息,
         遍历字典中所有的键-值对,所有的键和值
         如何在列表中嵌套字典,在字典中嵌套列表以及字典中嵌套字典










  • 相关阅读:
    windows下安装mysql教程
    python生成器实现杨辉三角
    python默认参数问题
    python中判断素数的函数
    extract()和extact_first()的区别
    硬连接和软连接的区别
    du与df的区别
    命题逻辑
    关于 better-scroll 设置了以后无法滚动或不生效的问题
    Maven *IDEA*
  • 原文地址:https://www.cnblogs.com/xzpin/p/10842341.html
Copyright © 2011-2022 走看看