Python字典

  1. 字典的键值是"只读"的,所以不能对键和值分别进行初始化,即以下定义是错的:

    >>> dic = {}
    >>> dic.keys = (1,2,3,4,5,6)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'dict' object attribute 'keys' is read-only
    >>> dic.values = ("a","b","c","d","e","f")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'dict' object attribute 'values' is read-only
    >>>
  2.  字典是支持无限极嵌套的,如下面代码:

    cities={
        '北京':{
            '朝阳':['国贸','CBD','天阶','我爱我家','链接地产'],
            '海淀':['圆明园','苏州街','中关村','北京大学'],
            '昌平':['沙河','南口','小汤山',],
            '怀柔':['桃花','梅花','大山'],
            '密云':['密云A','密云B','密云C']
        },
        '河北':{
            '石家庄':['石家庄A','石家庄B','石家庄C','石家庄D','石家庄E'],
            '张家口':['张家口A','张家口B','张家口C'],
            '承德':['承德A','承德B','承德C','承德D']
        }
    }

    可以使用如下方法进行列出

    for i in cities['北京']:
        print(i)

    将列出如下结果:

    朝阳
    海淀
    昌平
    怀柔
    密云
    for i in cities['北京']['海淀']:
        print(i)

    输出如下结果:

    圆明园
    苏州街
    中关村
    北京大学
  3.  用字典记录学生名字和分数,再分级:

    #!/usr/bin/python3
    
    students= {}
    write = 1
    while write :
        name = str(input('输入名字:'))
        grade = int(input('输入分数:'))
        students[str(name)] = grade
        write= int(input('继续输入?\n 1/继续  0/退出'))
    print('name  rate'.center(20,'-'))
    for key,value in students.items():
        if value >= 90:
            print('%s %s  A'.center(20,'-')%(key,value))
        elif 89 > value >= 60 :
            print('%s %s  B'.center(20,'-')%(key,value))
        else:
            print('%s %s  C'.center(20,'-')%(key,value))

    测试输出结果:

    输入名字:a
    输入分数:98
    继续输入?
     1/继续  0/退出1
    输入名字:b
    输入分数:23
    继续输入?
     1/继续  0/退出0
    -----name  rate-----
    ------a 98  A------
    ------b 23  C------
  4.  字典可以通过以下方法调换 key和 value,当然要注意原始 value 的类型,必须是不可变类型:

    dic = {
        'a': 1,
        'b': 2,
        'c': 3,
    }
    
    reverse = {v: k for k, v in dic.items()}
    
    print(dic)
    print(reverse)

    输出如下:

    {'a': 1, 'b': 2, 'c': 3}
    {1: 'a', 2: 'b', 3: 'c'}
  5. 循环显示字典 key 与 value 值:

    b= {'a':'runoob','b':'google'}
    for i in b.values():
        print(i)
    for c in b.keys():
        print(c)

    执行输出结果为:

    runoob
    google
    a
    b
  6. 字典字段的比较

    获取字典中最大的值及其键:

    prices = {
        'A':123,
        'B':450.1,
        'C':12,
        'E':444,
    }
    
    max_prices = max(zip(prices.values(), prices.keys()))
    print(max_prices) # (450.1, 'B')
  7. Python中会碰到这样的问题:

    >>> sites_link = {'runoog':'runoob.com', 'google':'google.com'}
    >>> sides = sites_link.keys()
    >>> print(sides[0])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'dict_keys' object does not support indexing
    >>>

    原因说明及解决方法:

    dict.values()
    dict.keys()

    在 python2.x dict.keys 返回一个列表,但是在在 Python 3.x 下,dict.keys 返回的是 dict_keys 对象,若需要转换为列表,请使用:

    list(dict.values())
    list(dict.keys())

    修改上面实例:

    >>> sites_link = {'runoog':'runoob.com', 'google':'google.com'}
    >>> sides = sites_link.keys()
    >>> list(sides)
    ['runoog', 'google']
    >>>
  8.  通过 values 取到 key 的方法:

    >>> dic={"a":1,"b":2,"c":3}
    >>> list(dic.keys())[list(dic.values()).index(1)]
    'a'
  9. 字典列表,即在列表中嵌套字典:

    dict_0 = {'color': 'green', 'points': 5} 
    dict_1 = {'color': 'yellow', 'points': 10} 
    dict_2 = {'color': 'red', 'points': 15}
    lists = [dict_0, dict_1, dict_2]
    for dict in lists: 
        print(dict)

    输出:

    {'color': 'green', 'points': 5} 
    {'color': 'yellow', 'points': 10} 
    {'color': 'red', 'points': 15}
  10. 字典推导式:

    格式:

    {key:value for variable in iterable [if expression]}

    执行步骤:

    •  1、for 循环:遍历可迭代对象,将其值赋给变量。
    •  2、if 语句:筛选满足 if 条件的结果。
    •  3、存储结构:以键值对的方式存储在字典中。
  11. dict.fromkeys() 存在一个坑:

    例如:

    l = [1,2,3]
    d = {}.fromkeys(l , [])

    这样得到的 d 是:

    {1:[] , 2:[] , 3:[]}

    其实这三个列表的地址是一样的,修改任意一个列表的值会导致所有列表的值都发生改变。

    可以使用这种方法来解决:

    d = {key : [] for key in l}
posted @ 2020-11-27 19:54  富贵儿-  阅读(353)  评论(0)    收藏  举报