zoukankan      html  css  js  c++  java
  • 【Python】学习笔记十:字典

    字典是Python中唯一的映射类型(哈希表)

    字典的对象时可变的,但字典的键值必须是用不可变对象,并且一个字典中可以使用不同类型的键值

    1.定义字典

            dict={key1:value1,key2:value2...}

    例子:

    >>> dict={'name':'OLIVER','age':24,'gender':'male'}
    >>> dict['name']
    'OLIVER'
    >>> dict['age']
    24
    >>> dict['gender']
    'male'

    2.特殊定义字典

    >>> a=100
    >>> b=101
    >>> dict4={a:'OLIVER','b':'QIN'}
    >>> dict4[100]
    'OLIVER'
    >>> dict4
    {100: 'OLIVER', 'b': 'QIN'}

     3.取出字典中的值

    这里以上述定义的dict为例子

    #获取key值
    >>> for k in dict:
    ... print(k)
    ...
    name
    age
    gender
    #获取value值
    >>> for k in dict:
    ...     print(dict[k])
    ...
    OLIVER
    24
    male

    4.字典key增加、删除、修改

    4.1增加

    >>> dict['tel']='12345678'
    >>> dict
    {'name': 'OLIVER', 'age': 24, 'tel': '12345678', 'gender': 'male'}

    4.2删除

    #删除其中一个元素
    >>> del(dict['tel'])
    >>> dict
    {'name': 'OLIVER', 'age': 24, 'gender': 'male'}
    
    #pop弹出某个元素,与del效果一样
    >>> dict.pop('age')
    24
    >>> dict
    {'name': 'OLIVER', 'gender': 'male'}
    >>>
    
    #清除所有元素
    >>> dict.clear()
    >>> dict
    {}
    
    #删除整个字典
    >>> del(dict)

    4.3修改

    >>> dict['tel']='0000000'
    >>> dict
    {'name': 'OLIVER', 'age': 24, 'tel': '0000000', 'gender': 'male'}

     5.字典中的get方法

    当所取key值在字典中不存在的时候,需要给出默认值,否则就会报错

    语法:dict.get(key,dafault=none):返回key的value,如果改键不存在,返回default指定的值。

    >>> dict5={'name':'jack','age':23}
    >>> dict5.get(4,'error')
    'error'
  • 相关阅读:
    2018/12/21 HDU-2077 汉诺塔IV(递归)
    2018-12-08 acm日常 HDU
    2018/12/12 acm日常 第二周 第六题
    git 添加远程分支,并可以code review.
    zookeeper数据迁移方法
    gem install nokogiri -v '1.6.6.2' 出错
    gem install json -v '1.8.2' error
    gem install bundle 安装失败
    全能型开源远程终端:MobaXterm
    如何写好 Git Commit 信息
  • 原文地址:https://www.cnblogs.com/OliverQin/p/6071874.html
Copyright © 2011-2022 走看看