• 技术文章 >Python技术 >Python基础教程

    python中如何遍历字典

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-12-21 10:34:27原创9274

    1. 遍历字典的键key

    python学习网,大量的免费python视频教程,欢迎在线学习!

    >>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)}
    >>> for key in d:
        print(str(key)+':'+str(d[key]))
    list:[1, 2, 3]
    1:123
    111:python3
    tuple:(4, 5, 6)

    相关推荐:《Python教程

    >>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)}
    >>> for key in d.keys():
        print(key)
    1
    list
    111
    tuple

    2. 遍历字典的值value

    >>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)}
    >>> for value in d.values():
        print (value)
    [1, 2, 3]
    123
    python3
    (4, 5, 6)

    3. 遍历字典的项

    >>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)}
    >>> for item in d.items():
        print(item)
    ('list', [1, 2, 3])
    (1, 123)
    ('111', 'python3')
    ('tuple', (4, 5, 6))

    4. 遍历字典的key-value

    >>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)}
    >>> for key,value in d.items():
        print(key,value)
    list [1, 2, 3]
    1 123
    111 python3
    tuple (4, 5, 6)

    >>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)}
    >>> for (key,value) in d.items():
        print(key,value)
    list [1, 2, 3]
    1 123
    111 python3
    tuple (4, 5, 6)
    专题推荐:python 遍历 字典
    上一篇:perl和python区别是什么 下一篇:python abs函数怎么用

    相关文章推荐

    • 教你用两种方式遍历循环python中的字典• python如何遍历dict

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网