• Python:dict用法


    dict全称dictionary,使用键-值(key-value)存储,有极快的查找速度。

    以下整理几种常用的dict用法

    定义

    空dict

    >>> dict={}

    普通dict

    >>> dict={'adele':'hello','taylor':'1989'}
    >>> dict
    {'taylor': '1989', 'adele': 'hello'}

    嵌套

    >>> a_dict={1:"{11:'a',12:'b'}",2:"2B",3:"3C"}
    >>> a_dict
    {1: "{11:'a',12:'b'}", 2: '2B', 3: '3C'}
    >>> a_dict[1][12]   
    'b'

    获取键、值

    key&values

    >>> a_dict.keys()
    [1, 2, 3]    #结果为list
    
    >>> a_dict.values() ["{11:'a',12:'b'}", '2B', '3C']

    items

    >>> a_dict.items()
    [(1, "{11:'a',12:'b'}"), (2, '2B'), (3, '3C')]  #结果为list,list里面的元素是元组

    for..in

    >>> for key in a_dict:
    ...     print (key)
    ... 
    1
    2
    3
    
    >>> for value in a_dict.values(): ... print(value) ... {11:'a',12:'b'} 2B 3C

       输出value等价语句

    >>> for key in  a_dict:
    ...     print a_dict[key]
    ... 
    {11:'a',12:'b'}
    2B
    3C

    同时输出键、值

    两种方法:

    1)使用两个变量k,v,完成循环

    2)使用一个变量k,通过k求出对应v

    >>> for k,v in a_dict.items():
    ...     print str(k)+":"+str(v)
    ... 
    1:{11:'a',12:'b'}
    2:2B
    3:3C
    

    >>> for k in a_dict: ... print str(k)+":"+str(a_dict[k]) ... 1:{11:'a',12:'b'} 2:2B 3:3C

      另一种实现形式

    >>> for k in a_dict:
    ...     print "a_dict(%s)="%k,a_dict[k]
    ... 
    a_dict(1)= {11:'a',12:'b'}
    a_dict(2)= 2B
    a_dict(3)= 3C

    get

    >>> a_dict.get(1)
    "{11:'a',12:'b'}"

    删除

    分别使用了三种方法:pop、del和clear

    >>> a_dict.pop('taylor')
    '1989'  #根据键值删除,并返回值
    
    >>> del a_dict[1] >>> a_dict {2: '2B', 3: '3C', 'adele': 'hello'}

    >>> a_dict.clear() >>> a_dict {}

    拷贝

    >>> new_dict=a_dict.copy()
    >>> new_dict
    {1: "{11:'a',12:'b'}", 2: '2B', 3: '3C'}

    合并

    >>> add_dict={'adele':'hello','taylor':'1989'}
    >>> a_dict.update(add_dict)
    >>> a_dict
    {1: "{11:'a',12:'b'}", 2: '2B', 3: '3C', 'adele': 'hello', 'taylor': '1989'}

    排序

    按照key排序

    >>> print sorted(a_dict.items(),key=lambda d:d[0])
    [(1, "{11:'a',12:'b'}"), (2, '2B'), (3, '3C')]   

     按照value排序

    >>> print sorted(a_dict.items(),key=lambda d:d[1])
    [(2, '2B'), (3, '3C'), (1, "{11:'a',12:'b'}")]

    后续使用中,再补充..

  • 相关阅读:
    分布式MySQL数据库TDSQL架构分析
    Vector Clock理解
    MySQL Full Join的实现
    HDU4309-Seikimatsu Occult Tonneru(最大流)
    UVA 10831
    jdk并发包 CopyOnWriteArrayList源代码分析
    Android源代码下载之《Android新闻client源代码》
    [背景分离] 识别移动物体基于高斯混合 MOG
    我与京东的那些事儿
    Android4.4 Framework分析——Zygote进程的启动过程
  • 原文地址:https://www.cnblogs.com/lilip/p/5553361.html
Copyright © 2020-2023  润新知