• 遍历字典


    Python支持对字典的遍历,有多种遍历字典的方式:所有的键值对,键或者值。

    遍历所有的键值对:

    people = {'name':'winter',
    'age':'25',
    'sex':'man',
    }
    for key,value in people.items():
    print(" key:"+key)
    print("value:"+value)

    key:name
    value:winter

    key:age
    value:25

    key:sex
    value:man
    favourite_language={'winter':'python',
    'thunder':'shell',
    'amy':'C'}
    for name,language in favourite_language.items():
    print(name.title()+"`s favourite language is "+language.title()+ ' .')


    Winter`s favourite language is Python .
    Thunder`s favourite language is Shell .
    Amy`s favourite language is C .

    遍历所有的键:
    favourite_language={'winter':'python',
    'thunder':'shell',
    'amy':'C'}
    for name in favourite_language.keys(): #遍历字典时默认遍历所有的键,因此key()方法加不加都可以,加上之后更容易理解。
    print(name)


    winter
    thunder
    amy
    按照顺序遍历所有键:
    favourite_language={'winter':'python',
    'thunder':'shell',
    'amy':'C'}
    for name in sorted(favourite_language.keys()): #利用sorted()函数对字典的键进行一个排序。
    print(name)


    amy
    thunder
    winter

    遍历所有的值:
    favourite_language={'winter':'python',
    'thunder':'shell',
    'amy':'C',
    'dongtian':'python'}
    for language in favourite_language.values(): #使用方法values()可以遍历字典所有的值。
    print(language)
    python
    shell
    C
    python
    这种做法提取字典中所有的值,但是没有考虑是否有重复的。
    favourite_language={'winter':'python',
    'thunder':'shell',
    'amy':'C',
    'dongtian':'python'}
    for language in set(favourite_language.values()): #使用方法values()可以遍历字典所有的值,使用set()函数可以使值为唯一的
    print(language)

    shell
    python
    C



     
  • 相关阅读:
    最长递增子序列
    Mit os Lab 2. Memory Management
    [ZZ]实现c协程
    Linux socket IO模型
    emacs简单入门
    令牌桶-流量控制
    GNU Makefile tips
    Linux atomic memory access
    [zz]Linux系统相关shell命令
    state thread
  • 原文地址:https://www.cnblogs.com/winter1519/p/9259197.html
Copyright © 2020-2023  润新知