zoukankan      html  css  js  c++  java
  • 字典的常用方法

    判断字典中是否存在某个键

    python3 中采用 in 方法

    #判断字典中某个键是否存在
    arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}
    #使用 in 方法
    if "int" in arr:
        print("存在")
    if "float" in arr.keys():
        print("存在")
    #判断键不存在
    if "floats" not in arr:
        print("不存在")
    if "floats" not in arr:
        print("不存在")
    

    python 3中不支持 has_key(),python2 中支持

    #判断字典中某个键是否存在
    arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}
    #使用自带的has_key()
    if(arr.has_key("int")):
        print("存在")
    

    遍历字典

    1.遍历key值

    >>> a
    {'a': '1', 'b': '2', 'c': '3'}
    >>> for key in a:
           print(key+':'+a[key])
     
    a:1
    b:2
    c:3
    >>> for key in a.keys():
           print(key+':'+a[key])
     
    a:1
    b:2
    c:3
    

    在使用上,for key in a和 for key in a.keys():完全等价。

    2.遍历value值

    >>> for value in a.values():
           print(value)
     
    1
    2
    3
    

    3.遍历字典项

    >>> for kv in a.items():
           print(kv)
     
    ('a', '1')
    ('b', '2')
    ('c', '3')
    

    4.遍历字典健值

    >>> for key,value in a.items():
           print(key+':'+value)
     
    a:1
    b:2
    c:3
    >>> for (key,value) in a.items():
           print(key+':'+value)
     
    a:1
    b:2
    c:3
    

    在使用上for key,value in a.items()与for (key,value) in a.items()完全等价

    参考:

  • 相关阅读:
    js笔记4
    js笔记3
    js笔记2
    js笔记1
    前端笔记13
    (7)第3章的开始
    (6)第2章的尾巴~
    (5)自定义数据结构再探
    我的学习方法(6)
    (4)自定义数据结构初探
  • 原文地址:https://www.cnblogs.com/yuwq/p/11495963.html
Copyright © 2011-2022 走看看