zoukankan      html  css  js  c++  java
  • 字典

      字典是另一种可变容器模型,且可存储任意类型对象。

      字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})

    dict = {key1 : value1, key2 : value2 }

      字典的特性:键必须是唯一的,但值则不必唯一。

    【1】定义

     值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

     字典实例:

    dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
    dict2 = { 'abc': 123, 98.6: 37 };

    【2】访问字典的值

      使用 obj[key] 的形式

    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'webFont'
    }
    print(dict['name'])
    #hugo
    print(dict['age'])
    #18
    print(dict['position'])
    #webFont

      假如字典里没有的键访问数据,会输出错误:

    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'webFont'
    }
    print(dict['work'])

      报错如下:

    File "/Users/hugo/Desktop/test/test.py", line 6, in <module>
        print(dict['work'])
    KeyError: 'work'

    【3】修改字典

    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'webFont'
    }
    dict['age'] = 20
    print(dict)
    #{'name': 'hugo', 'age': 20, 'position': 'webFont'}

    【4】增加字典的键和值

      假如字典中有这个键和这个键所对应的值,则是对字典键所对应的值的修改;假如字典中没有这个键和这个键所对应的值,则是对字典添加键值对

    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'webFont'
    }
    #这个是修改
    dict['age'] = 20
    #这个是添加键值对
    dict['sex'] = 'man'
    print(dict)
    #{'name': 'hugo', 'age': 20, 'position': 'webFont', 'sex': 'man'}

    【5】删除字典元素

    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'webFont'
    }
    #删除键 'name'
    del dict['name']
    print(dict)
    #{'age': 18, 'position': 'webFont'}
    #清空字典
    dict.clear()
    print(dict)
    #{}
    #删除字典
    del dict
    print(dict)
    #<class 'dict'>

      在字典的内置函数中会介绍到其它删除方法

    【6】字典的特性

      键必须是唯一的,但值则不必唯一。

      1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例

    dict = {'Name': 'Runoob', 'Age': 7, 'Name': '小菜鸟'}
    print (dict['Name'])
    #小菜鸟

      2)键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行,如下实例:

    dict = {['Name']: 'Runoob', 'Age': 7}
    print ("dict['Name']: ", dict['Name'])

      报错如下:

    Traceback (most recent call last):
      File "/Users/hugo/Desktop/test/ss.py", line 1, in <module>
        dict = {['Name']: 'Runoob', 'Age': 7}
    TypeError: unhashable type: 'list'

    【7】字典的嵌套

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

    【8】字典的内置函数

    序号函数及描述实例
    1 len(dict)
    计算字典元素个数,即键的总数。
    >>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
    >>> len(dict)
    3
    2 str(dict)
    输出字典,以可打印的字符串表示。
    >>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
    >>> str(dict)
    "{'Name': 'Runoob', 'Class': 'First', 'Age': 7}"
    3 type(variable)
    返回输入的变量类型,如果变量是字典就返回字典类型。
    >>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
    >>> type(dict)
    <class 'dict'>

    【9】字典的内置方法:

    • clear() 删除字典内所有元素
    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'webFont'
    }
    dict.clear()
    print(dict)
    #{}
    • copy() 返回一个字典的浅复制
    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'webFont'
    }
    dict1 = dict.copy()
    print(dict1)
    #{'name': 'hugo', 'age': 18, 'position': 'webFont'}

      关于字典的深浅拷贝的理解,点击此

    • fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值,返回列表

      语法如下

    dict.fromkeys(seq[, value]))

    参数:
    seq--字典值列表
    value--可选参数,设置键序列(seq)的值
    seq = ('name', 'age', 'sex')
    
    dict = dict.fromkeys(seq)
    print ("新的字典为 : %s" %  str(dict))
    #新的字典为 : {'name': None, 'age': None, 'sex': None}
    dict = dict.fromkeys(seq, 10)
    print ("新的字典为 : %s" %  str(dict))
    #新的字典为 : {'name': 10, 'age': 10, 'sex': 10}
    • get() 返回指定键的值,如果值不在字典中返回default值

      语法和例子如下:

    dict.get(key, default=None)
    参数:
        key-- 字典中要查找的键
        default -- 如果指定键的值不存在时,返回该默认值值。
    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'web'
    }
    print(dict.get('age'))
    # 10
    print(dict.get('position'))
    #web
    print(dict.get('Sex',"man"))
    #man
    •  in 操作符用于判断键是否存在于字典中,如果键在字典dict里返回true,否则返回false。

      语法和例子如下:

    key in dict
    参数:
        key-- 要在字典中查找的键。
    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'web'
    }
    print('name' in dict)
    # True
    print('sex' in dict)
    # False
    •  items() 方法以列表返回可遍历的(键, 值) 元组数组

      语法和例子如下:

    dict.items()
    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'web'
    }
    print(dict.items())
    #dict_items([('name', 'hugo'), ('age', 18), ('position', 'web')])
    • keys() 方法以列表返回一个字典所有的键。

      语法和例子如下:

    dict.keys()
    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'web'
    }
    print(dict.keys())
    #dict_keys(['name', 'age', 'position'])
    •  setdefault() 方法和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值

      语法和例子如下:

    dict.setdefault(key, default=None)
    参数
        key -- 查找的键值。
        default -- 键不存在时,设置的默认键值。
    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'web'
    }
    print(dict.setdefault('age', None))
    #18
    print(dict.setdefault('sex', None))
    #None
    print(dict)
    #{'name': 'hugo', 'age': 18, 'position': 'web', 'sex': None}
    • update() 函数把字典dict2的键/值对更新到dict里。

      语法和例子如下:

    dict.update(dict2)
    参数:
        dict2 -- 添加到指定字典dict里的字典。
    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'web'
    }
    dict2= {
        'sex': 'man'
    }
    dict.update(dict2)
    print(dict)
    #{'name': 'hugo', 'age': 18, 'position': 'web', 'sex': 'man'}
    • values() 方法以列表返回字典中的所有值。

      语法和例子如下:

    dict.values()
    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'web'
    }
    print(dict.values())
    #dict_values(['hugo', 18, 'web'])
    • pop() 方法删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。

      语法和例子如下:

    pop(key[,default])
    参数
        key: 要删除的键值
        default: 如果没有 key,返回 default 值
    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'web'
    }
    
    print(dict.pop('name'))
    #hugo
    print(dict)
    #{'age': 18, 'position': 'web'}
    print(dict.pop('sex','man'))
    #man
    print(dict)
    #{'age': 18, 'position': 'web'}
    •  popitem() 方法随机返回并删除字典中的一对键和值(一般删除末尾对)。
    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'web'
    }
    print(dict.popitem())
    #('position', 'web')
    print(dict)
    #{'name': 'hugo', 'age': 18}

    【10】遍历

      通过for ... in ...:的语法结构,我们可以遍历字符串、列表、元组、字典等数据结构。

      1、字符串的遍历

    aString = "hello world"
    for char in aString:
        print(char, end= " ")
    #h e l l o   w o r l d

      2、列表的遍历

    aList = [1, 2, 3, 4, 5]
    for num in aList:
        print(num,end=' ')
    #1 2 3 4 5

      3、元祖的遍历

    aTurple = (1,2,3,4,5)
    for num in aTurple:
        print(num, end=" ")
    #1 2 3 4 5

    【11】字典的遍历

      1、遍历字典的键(key)

    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'web'
    }
    for key in dict.keys():
        print(key)
    #name
    #age
    #position

      2、遍历字典的值(value)

    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'web'
    }
    
    for val in dict.values():
        print(val)
    #hugo
    #18
    #web

      3、遍历字典的项

    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'web'
    }
    for item in dict.items():
        print(item)
    #('name', 'hugo')
    #('age', 18)
    #('position', 'web')

      4、遍历字典的key-value (键值对)

    dict = {
        'name': 'hugo',
        'age': 18,
        'position': 'web'
    }
    for key,value in dict.items():
        print("key=%s,value=%s"%(key,value))
    #key=name,value=hugo
    #key=age,value=18
    #key=position,value=web

      

  • 相关阅读:
    IssueQuery failed in redmine rake tasks
    rubymine 调试 redmine
    redmine rake tasks
    rails tutorial sample app
    win7 chm 打开失败记录
    rails再体验(第一个程序)
    Bitnami Redmine插件开发记录
    redmine export long csv file failed: 502 proxy error
    Java时区切换时的需要注意
    Android No static field XXX of type I in class Lcom/XXX/R$id错
  • 原文地址:https://www.cnblogs.com/Jiangchuanwei/p/8487343.html
Copyright © 2011-2022 走看看