zoukankan      html  css  js  c++  java
  • python数据类型之字典

    python数据类型之字典

    数据类型—字典dict

    特性:无序,key-value的结构存储数据,查找速度快

    key必须是可hash数据类型,且是唯一的,value可以是任意的。

    官方帮助文档

    1. Help on class dict in module builtins: 
    2.  
    3. class dict(object) 
    4. | dict() -> new empty dictionary 
    5. | dict(mapping) -> new dictionary initialized from a mapping object's 
    6. | (key, value) pairs 
    7. | dict(iterable) -> new dictionary initialized as if via: 
    8. | d = {} 
    9. | for k, v in iterable: 
    10. | d[k] = v 
    11. | dict(**kwargs) -> new dictionary initialized with the name=value pairs 
    12. | in the keyword argument list. For example: dict(one=1, two=2
    13. |  
    14. | Methods defined here: 
    15. |  
    16. | clear(...) 
    17. | D.clear() -> None. Remove all items from D. 
    18. |  
    19. | copy(...) 
    20. | D.copy() -> a shallow copy of D 
    21. |  
    22. | fromkeys(iterable, value=None, /) from builtins.type 
    23. | Returns a new dict with keys from iterable and values equal to value. 
    24. |  
    25. | get(...) 
    26. | D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None
    27. |  
    28. | items(...) 
    29. | D.items() -> a set-like object providing a view on D's items 
    30. |  
    31. | keys(...) 
    32. | D.keys() -> a set-like object providing a view on D's keys 
    33. |  
    34. | pop(...) 
    35. | D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 
    36. | If key is not found, d is returned if given, otherwise KeyError is raised 
    37. |  
    38. | popitem(...) 
    39. | D.popitem() -> (k, v), remove and return some (key, value) pair as
    40. | 2-tuple; but raise KeyError if D is empty. 
    41. |  
    42. | setdefault(...) 
    43. | D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in
    44. |  
    45. | update(...) 
    46. | D.update([E, ]**F) -> None. Update D from dict/iterable E and F. 
    47. | If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] 
    48. | If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v 
    49. | In either case, this is followed by: for k in F: D[k] = F[k] 
    50. |  
    51. | values(...) 
    52. | D.values() -> an object providing a view on D's values 
    53. |  
    54. | ---------------------------------------------------------------------- 
    55. | Data and other attributes defined here: 
    56. |  
    57. | __hash__ = None 


    创建字典

    字典的key必须是不可数据类型、且必须是唯一的
    class dict(object)
    | dict() -> new empty dictionary
    | dict(mapping) -> new dictionary initialized from a mapping object's
    | (key, value) pairs
    | dict(iterable) -> new dictionary initialized as if via:
    | d = {}
    | for k, v in iterable:
    | d[k] = v
    | dict(**kwargs) -> new dictionary initialized with the name=value



    直接创建
    >>> a = {'name':'james','age':25}
    >>> a
    {'name': 'james', 'age': 25}
    
    通过dict创建
    >>> a = ('name','alex'),('age', 38)
    >>> a
    (('name', 'alex'), ('age', 38))
    >>> dict(a)
    {'name': 'alex', 'age': 38}
    
    关键字创建
    >>> dict(name = 'alex',age = 38)
    {'name': 'alex', 'age': 38}
    


    字典的方法

    ['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
    

    增加

    1. 存在就覆盖,不存在就覆盖 
    2. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    3. >>> dic1['high'] = 175 # 不存在key = 'high'才新增,如果存在就是覆盖 
    4. >>> dic1 
    5. {'name': 'james', 'age': 18, 'sex': 'male', 'high': 175
    6. dic1.setdefalut(key,value)  # 字典中存在key,不做任何改变,不存在就新增,value不指定时默认为None 
    7. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    8. >>> dic1.setdefault("name",'JAMES') # 字典中存在key为'name'的键值对,直接返回key对应的值,字典没有改变 
    9. 'james' 
    10. >>> dic1 
    11. {'name': 'james', 'age': 18, 'sex': 'male'}  
    12. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    13. >>> dic1.setdefault('weight',130) # 字典中不存在key = 'weight',就新增进去,返回value 
    14. 130 
    15. >>> dic1 
    16. {'name': 'james', 'age': 18, 'sex': 'male', 'weight': 130


    删除

    1. dic1.pop(key,x) 
    2. 指定key值删除,如果key存在,返回key对应的value,x缺失的情况下,key不存在会报错。指定x,key不存在返回x,不会报错。  
    3. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    4. >>> dic1.pop('age') # 不指定x,key存在返回key的value 
    5. >>> dic1 
    6. {'name': 'james', 'sex': 'male'
    7. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    8. >>> dic1.pop("high") # 不指定x,key不存在报错 
    9. Traceback (most recent call last): 
    10. File "<pyshell#24>", line 1, in <module> 
    11. dic1.pop("high"
    12. KeyError: 'high' 
    13. 如果指定了x,key不存在时,直接返回x;如果指定x,key存在就直接返回key对应的value(可设置返回值x) 
    14. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    15. >>> dic1.pop("high",178)  
    16. dic1.popitem() # 随机删除,有返回值,返回以元组形式的键值。 
    17. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    18. >>> dic1.popitem() 
    19. ('sex', 'male'
    20. del dic1.[key] # 按照指定的key删除键值,没有返回值,如果key不存在会报错 
    21. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    22. >>> del dic1.['heigh'
    23. SyntaxError: invalid syntax  
    24. del dic1 # 直接删除字典 
    25. dic1.clear() #清空列表 


    修改

    1. 赋值修改 
    2. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    3. >>> dic1['name'] = 'JAMES' # 直接对指定的key值对应的value进行赋值修改 
    4. >>> dic1 
    5. {'name': 'JAMES', 'age': 18, 'sex': 'male'
    6. dic1.update(dic2) # 更新  
    7. 把dic2的键值对更新到dic1中,相同key值的,覆盖掉dic1中的value,dic1中的没有的key,新增进去 
    8. dic1法生改变,dic2不发生改变 
    9. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    10. >>> dic2 = {'name':'tony','heigh':178
    11. >>> dic1.update(dic2) 
    12. >>> dic1 
    13. {'name': 'tony', 'age': 18, 'sex': 'male', 'heigh': 178
    14. >>> dic2 
    15. {'name': 'tony', 'heigh': 178


    查询

    1. 第一种:dic1[key] 按照指定的key,找出对应的value,如果key不存在,会报错 
    2. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    3. >>> dic1['name'
    4. 'james' 
    5. >>> dic1['high'
    6. Traceback (most recent call last): 
    7. File "<pyshell#43>", line 1, in <module> 
    8. dic1['high'
    9. KeyError: 'high'  
    10. 第二种:dic1.get(key,x) 查找对应键的值,可设置返回值,x默认是None 
    11. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    12. >>> dic1.get('name') # 如果存在返回对应的value 
    13. 'james' 
    14. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    15. >>> dic1.get('heigh','不存在') # 如果key不存在,返回x指定的值,x为空默认返回None 
    16. '不存在'  
    17. dic1.keys() 返回字典里面的全部key,以列表的形式返回 
    18. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    19. >>> dic1.keys() 
    20. dict_keys(['name', 'age', 'sex'])  
    21. dic1.values() 返回字典里面的全部value,以列表的形式返回 
    22. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    23. >>> dic1.values() 
    24. dict_values(['james', 18, 'male'])  
    25. dic1.items() 把字典的键和值放进元组,以列表的形式返回 
    26. >>> dic1 = {'name':'james', 'age':18, 'sex':'male'
    27. >>> dic1.items() 
    28. dict_items([('name', 'james'), ('age', 18), ('sex', 'male')]) 

    字典的其他方法

    fromkeys(iterable, value=None, /) method of builtins.type instance
    Returns a new dict with keys from iterable and values equal to value.

    1. >>> a = 'name' 
    2. >>> dict.fromkeys(a) 
    3. {'n': None, 'a': None, 'm': None, 'e': None
    4. >>> b = [21,22,23
    5. >>> dict.fromkeys(a,b) 
    6. {'n': [21, 22, 23], 'a': [21, 22, 23], 'm': [21, 22, 23], 'e': [21, 22, 23]} 

    复制

    copy(...) method of builtins.dict instance
    D.copy() -> a shallow copy of D
    查看链接

    字典的循环

    >>> for index,k in enumerate(a):
        print(index,k)      
    0 name
    1 age
    2 sex
    
    >>> for k in a:
              print(k,a[k])      
    name peiqi
    age 38
    sex male
    
  • 相关阅读:
    把 html标签转化为 html标签代码
    手动创建sql数据表
    “亚信科技杯”南邮第七届大学生程序设计竞赛之网络预赛 A noj 2073 FFF [ 二分图最大权匹配 || 最大费用最大流 ]
    “亚信科技杯”南邮第七届大学生程序设计竞赛之网络预赛 G Prime [ 容斥原理 + 数论 + 求约数 + 素数筛 ]
    “亚信科技杯”南邮第七届大学生程序设计竞赛之网络预赛 (部分题解)
    “亚信科技杯”南邮第七届大学生程序设计竞赛之网络预赛 (K L题解)
    hdu 5195 DZY Loves Topological Sorting BestCoder Round #35 1002 [ 拓扑排序 + 优先队列 || 线段树 ]
    noj 2033 一页书的书 [ dp + 组合数 ]
    Codeforces Round #297 (Div. 2) D. Arthur and Walls [ 思维 + bfs ]
    hdu 1728 逃离迷宫 [ dfs ]
  • 原文地址:https://www.cnblogs.com/james201133002/p/9437009.html
Copyright © 2011-2022 走看看