zoukankan      html  css  js  c++  java
  • python 字典

    (1)Properties:
    No order, No repeat, implemented by hash_table

    Note: key is immutable, it must can be hashed, so the type of key must be immutable, such as digit, string, or tuple.
    dic = {'a':1 , 'b':2 , 'c': 3}, there is no order for the element, so dict[0] is in a SyntaxError.

    but, initial dict, and print it, the print consequence may be different from the initialization order. (because of the function of hash_table).
    dic.add['c'] = 4 ==> {'a':1 , 'b':2 , 'c': 4}
    (2)common methods
    items() ## # get all element one time, and return a list
    iteritems() ##> return a iterator for the dict element
    example:
    >>> D.items() #all elements, using "for" traverse
    [('a', 1), ('c', 3), ('b', 2), ('d', 4)] 
    >>> D.iteritems() 
    <dictionary-itemiterator object at 0x00000000026243B8>

    (3)sort for dict(using build-in: sorted)
    function prototype:sorted(dic,value,reverse)
    eg. 1:
    dic = {'a':31, 'bc':5, 'c':3, 'asd':4, '33':56, 'd':0}
    print sorted(dic.iteritems(), key=lambda d:d[1], reverse = False ) 

    #[('d', 0), ('c', 3), ('asd', 4), ('bc', 5), ('a', 31), ('33', 56)]

    interpretation: 

    >> Starting with Python 2.4, both list.sort() and sorted() added a key parameter

    >> to specify a function to be called on each list element prior to making comparisons.


    EG. 2:

    >>> sorted(list(dic), key=lambda d:d[1], reverse=False)
    Traceback (most recent call last):
    File "<pyshell#36>", line 1, in <module>
    sorted(list(dic), key=lambda d:d[1], reverse=False)
    File "<pyshell#36>", line 1, in <lambda>
    sorted(list(dic), key=lambda d:d[1], reverse=False)
    IndexError: string index out of range
    >>> sorted(list1) ##OK
    (4)traverse dict
    dic={'a':'12', 'we':'90', 'dd':'dd'}
    for key in dic:
    print key
    EG. 2:
    dic={'a':'12', 'we':'90', 'dd':'dd'}
    for value in dic.values():
    print value
    (5)delete dict
    del dic['a']
    dic.clear()
    del dic

    (6)merge two dict

    dict1.update(dict2)

    http://www.cnblogs.com/dkblog/archive/2012/02/02/2336089.html

    (7) create dict

      * directly

      * dict()

      * build-in function: fromkeys(seq[,value]):  dict1={}.fromkeys(('x','y'),-1)

      * create dict by two list:

    >>> dt=dict(zip(keys,values))
    >>> dt
    {1: 'aa', 2: 'bb', 3: 'cc', 4: 'dd'}

  • 相关阅读:
    更换Ubuntu源为国内源的操作记录
    Dockerfile构建容器镜像
    Nginx负载均衡中后端节点服务器健康检查
    Linux系统下CPU使用(load average)梳理
    android:怎么实现一个控件与另一个指定控件左对齐
    Android Studio一直 Fetching Documentation...
    px、pt、ppi、dpi、dp、sp之间的关系
    Android中如何在代码中设置View的宽和高?
    硬中断与软中断的区别!
    Java 日期时间获取和显示
  • 原文地址:https://www.cnblogs.com/lifeinsmile/p/5405959.html
Copyright © 2011-2022 走看看