zoukankan      html  css  js  c++  java
  • python字典-字典方法

    1.kyes()

    (1)取出字典的key

    In [32]: myCat
    Out[32]: {'colr': 'gray', 'size': 'fat'}
    
    In [33]: for i in myCat.keys():
        ...:     print(i)
        ...:
    size
    colr

    (2)检查字典中是否存在键或值

    2.values()

    (1)取出字典的value

    In [39]: for i in myCat.values():
        ...:     print(i)
        ...:
    fat
    gray

    3.items()

    (1)取出字典的key和value

    In [50]: for i in myCat.items():
        ...:     print(i)
        ...:
    ('size', 'fat')
    ('colr', 'gray')


    (2)多重赋值

    In [58]: myCat
    Out[58]: {'colr': 'gray', 'size': 'fat'}
    
    In [59]: for k,v in myCat.items():
        ...:     print("key: " + k + " values: "+ v)
        ...:
    key: size values: fat
    key: colr values: gray

    4.类型转化

    (1)通过ist(),生成列表

    In [61]: myCat
    Out[61]: {'colr': 'gray', 'size': 'fat'}
    
    In [62]: myCatlist = list(myCat.keys())
    
    In [63]: myCatlist
    Out[63]: ['size', 'colr'] 

    5.get()方法

    (1)get()方法有两个参数:要取得其值的键;以及如果该键不存在时,返回的备用值。

     6.setdefault()方法

    为字典中的键设置默认值,当该键没有任何值时使用它。

    setdefault()方法提供了一种方式,在一行中完成这件事。传递给该方法的第一 个参数,是要检查的键。第二个参数,是如果该键不存在时要设置的值。如果该键 确实存在,方法就会返回键的值。

    7.删除key

    (1)del
    删除字典中某组键值对

    In [64]: myCat
    Out[64]: {'colr': 'gray', 'size': 'fat'}
    
    In [65]: del myCat['colr']
    
    In [66]: myCat
    Out[66]: {'size': 'fat'}

    (2)clear()

    清空字典

    In [67]: myCat
    Out[67]: {'size': 'fat'}
    
    In [68]: myCat.clear()
    
    In [69]: myCat
    Out[69]: {}

    (3)pop()

    删除字典中某组键值对,并返回值

    In [78]: myCat
    Out[78]: {'colr': 'gray', 'size': 'fat'}
    
    In [79]: myCat.pop('colr')
    Out[79]: 'gray'
    
    In [80]: myCat
    Out[80]: {'size': 'fat'}

    (4)pop.item()

    随机删除一个键值对

    In [82]: myCat = {'colr': 'gray', 'size': 'fat',}
    
    In [83]: myCat.popitem()
    Out[83]: ('size', 'fat')

    练习

     characterCount.py计算message中每个字符出现的次数

    #!/usr/bin/env python
    #coding:utf-8
    from pprint import *

    message = 'It is bright cold day in April, and the clocks where the striking thirteen.'
    count = {} #字典

    for character in message:
    count.setdefault(character,0) #character=key,value默认=0
    count[character] = count[character] + 1 #为key设置value,value=value+1

    pprint(count)  #pprint能够对key排序






  • 相关阅读:
    《金字塔原理》听书笔记
    凡事有交代
    关于马云不用淘宝不用支付宝的想法
    jenkins如何在一台机器上开启多个slave
    jenkins结合docker
    flask-assets使用介绍
    touch: cannot touch ‘/var/jenkins_home/copy_reference_file.log’: Permission denied Can not write to /var/jenkins_home/copy_reference_file.log. Wrong volume permissions?
    JS中event.preventDefault()取消默认事件能否还原?
    flask前端优化:css/js/html压缩
    What's New In DevTools (Chrome 59)来看看最新Chrome 59的开发者工具又有哪些新功能
  • 原文地址:https://www.cnblogs.com/dingkailinux/p/8216087.html
Copyright © 2011-2022 走看看