zoukankan      html  css  js  c++  java
  • Python基础(3)

    Python 

    Dictionary 是 Python 的内置数据类型之一, 它定义了键和值之间一对一的关系 。它是用{}括起来的。每个Dictionary的项的句法为:key:value. Dictionary就象我们熟知的hash表。

    >>> d = {'key1':'value1','key2':'value2'}
    >>> d
    {'key2': 'value2', 'key1': 'value1'}
    >>> d['key1']
    'value1'
    >>> d['key3']
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'key3'

    当Key不存在时,会引发一个异常。

    Dictionary的相关操作:

    >>> d = {'key1':'value1','key2':'value2'}
    >>> d['key3'] = 'value3' #新增元素
    >>> d['key3'] = 1 #可以是任意类型
    >>> del d['key1'] #删除单个元素
    >>> d.clear() 

    Dictionary的key可以是 数字,字符串,元组等不可变类型

    Dictionary元素的顺序并不是按照增加的顺序进行排序的。Dictionary中的元素是没有顺序概念的。

    Dictionary的遍历:

    >>> d = {'key1':'value1','key2':'value2'}
    >>> for key in d.keys():
    ...     print key, d[key]
    ...
    key2 value2
    key1 value1
    >>> for key in d:
    ...     print key, d[key]
    ...
    key2 value2
    key1 value1
    >>>

    从python2.2开始,可以不必再用keys()方法获取供循环使用的键值列表,可以用迭代器访问,即:只要用字典的名字就可以在for循环内遍历字典

    从python2.3开始,调用dict()方法可以接受字典或关键字参数创建字典:

    >>> d = dict(x=1,y=2)
    >>> d
    {'y': 2, 'x': 1}
    >>> d2 = d.copy()
    >>> d2
    {'y': 2, 'x': 1}

    dict.clear() removes all elements of dictionary dict

    dict.copy() returns a (shallow) copy of dictionary dict

    dict.get(key, default=None) for key key, returns value or default if key not in dictionary (note that default's default is None)

    dict.has_key(key) returns 1 if key in dictionary dict, 0 otherwise

    dict.items() returns a list of dict's (key, value) tuple pairs

    dict.keys() returns list of dictionary dict's keys

    dict.setdefault(key, default=None) similar to get(), but will set dict[key]=default if key is not already in dict

    dict.update(dict2) adds dictionary dict2's key-values pairs to dict

    dict.values() returns list of dictionary dict's values

    dict.fromkeys(seq,val=None) 创建并返回一个新字典,以seq中的元素做该字典的键,val做字典中所有键对应的初始值

    dict.sort( ) 排序

    字典解析:

    大家熟悉的列表解析:

    从python2.7开始,可以用同样的语法创建字典:

    >>> d = { x: x % 2 == 0 for x in range(1, 11) }

    >>> d

    {1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}

  • 相关阅读:
    Paddle和PaddleNLP的简介与使用
    Hangfire 使用笔记 任务可以分离到别的项目中,无需重复部署Hangfire,通过API方式通信。
    DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead driver.find_element_by_class_name('content-wrapper-inner').click()
    图片反防盗链
    onsubmit=return false阻止form表单提交
    360极速浏览器安装vue-devtools插件
    Node.js安装详细步骤教程(Windows版)
    C/C++ for Visual Studio Code
    mysql 利用ibd文件恢复数据库
    解决 本地计算机上的MySQL80服务启动后停止的问题!!!
  • 原文地址:https://www.cnblogs.com/TonyZhao/p/3527779.html
Copyright © 2011-2022 走看看