• [每日一讲] Python系列:字典


    #! /usr/bin/python
    # coding:utf-8
    """
    DATA STRUCTURE
        Container: Mapping (Another container is Set)
            —— Dict
    Dict is the only one type of Mapping in python. It's unordered.
    To define a dict, use symbol '{ }', stored by 'K-V' form.
    So, while index method, such as List/Tuple, is invalid. we can use
    Dict.
    
    note: dict() is the function to create a new dictionary.
    
    数据结构
        容器:映射(另外一个容器是 Set '集')
            —— 字典
    在 python 中字典是唯一的映射类型。它是无序的。
    定义一个字典,使用符号'{ }',以 K-V 的形式存储。
    所以,当以列表/数组的方式索引不适用时,我们用字典来代替。
    
    注意:函数 dict() 是用来创建一个新的字典。
    """
    

    #! /usr/bin/python
    # coding:utf-8
    
    
    class DictAction:
    
        def __init__(self):
            pass
    
        @staticmethod
        def dict_formatter():
            phone_book = {'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
            # template as usual
            res = "Cecil's phone number is {Cecil}.".format_map(phone_book)
            print(res)
    

    1 dict.clear()
    删除字典内所有元素
    2 dict.copy()
    返回一个字典的浅复制
    3 dict.fromkeys(seq[, val])
    创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值
    4 dict.get(key, default=None)
    返回指定键的值,如果值不在字典中返回default值
    5 dict.has_key(key)
    如果键在字典dict里返回true,否则返回false
    6 dict.items()
    以列表返回可遍历的(键, 值) 元组数组
    7 dict.keys()
    以列表返回一个字典所有的键
    8 dict.setdefault(key, default=None)
    和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
    9 dict.update(dict2)
    把字典dict2的键/值对更新到dict里
    10 dict.values()
    以列表返回字典中的所有值
    11 pop(key[,default])
    删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
    12 popitem()
    随机返回并删除字典中的一对键和值。

  • 相关阅读:
    (二十五)Struts2 Tiles集成
    (二十四)Struts2 Spring集成
    etcd 和 redis的使用场景
    react v16.12 源码阅读环境搭建
    gmail邮箱怎么批量删除邮件
    动态创建的元素怎么做动画
    Window 添加定时任务
    commons-pool2-中的一些配置
    Activiti 5.18 流程Model 转成 流程BPMN文件
    Activiti 使用自己的身份认证服务
  • 原文地址:https://www.cnblogs.com/hailongchen/p/10872897.html
Copyright © 2020-2023  润新知