• Python 基础


     Dictionary的表达式:{KEY: VALUE} 

    • value 可以是string, list, or disctionary.  层层嵌套,e.g 多层菜单
    • Dictionary的打印结果是无序的。因为可以通过key来查找value内容,所有不用像list一样,通过下标来查找。
    • key必须是唯一的,天生去重复。
    Dataset = {
        'Equity Fund': 'Deep value',
        'Balanced Fund': 'Market oriented with a growth bias',
        'Fixed Income Fund': ['Government bond','Financial Notes','Credit Bond','MBS'],
    }
    print(Dataset)

    {'Equity Fund': 'Deep value', 'Balanced Fund': 'Market oriented with a growth bias', 'Fixed Income Fund': ['Government bond', 'Financial Notes', 'Credit Bond', 'MBS']}

    •  dict([container]) : 创建字典的工厂函数。如果提供了容器类(container),作为一个参数传递给dict(), 如果这个参数是可以迭代的,那每个可迭代的元素必须成对出现。每个值对中,第一个元素是key,第二个是value
    Dataset3 = dict(zip(('x','y'),(1,2)))  #方法1
    Dataset3 = dict([['x',1],['y',2]])      #方法2
    Dataset3 = dict([('xy'[i-1],i) for i in range(1,3)])   #方法3
    
    print(Dataset3)

    {'x': 1, 'y': 2}

    •  内建函数fromkey的使用(最好少用,这是万能坑)
    Dictionary1 = dict.fromkeys(['key1','key2','key3'], ['value1','value2','value3'])
    print(Dictionary1)

    {'key1': ['value1', 'value2', 'value3'], 'key2': ['value1', 'value2', 'value3'], 'key3': ['value1', 'value2', 'value3']}
    但是,当要修改具体value值时,

    Dictionary1['key2'][2] ='VALUE3'
    print(Dictionary1)

     {'key1': ['value1', 'value2', 'VALUE3'], 'key2': ['value1', 'value2', 'VALUE3'], 'key3': ['value1', 'value2', 'VALUE3']}

    原因和浅copy是一样的, 内存地址一致,所有都改掉了。

    添加

    Dataset["Alternative Investment"] = 'REITS'  # 添加Key
    print(Dataset)

    {'Equity Fund': 'Deep value', 'Balanced Fund': 'Market oriented with a growth bias', 'Fixed Income Fund': ['Government bond', 'Financial Notes', 'Credit Bond', 'MBS'], 'Alternative Investment': 'REITS'}

    修改

    Dataset["Equity Fund"] = 'Fundamental Growth'
    Dataset['Fixed Income Fund'][1] = 'MTN'
    print(Dataset)

    {'Equity Fund': 'Fundamental Growth', 'Balanced Fund': 'Market oriented with a growth bias', 'Fixed Income Fund': ['Government bond', 'MTN', 'Credit Bond', 'MBS'], 'Alternative Investment': 'REITS'}

    删除

    del Dataset['Equity Fund']
    print(Dataset)

    or 

    Dataset.pop("Equity Fund") 
    print(Dataset)

    or 随机删除

    Dataset.popitem()

    查找/访问

    print("Equity Fund" in Dataset)   # 判断是否存在于字典

    True

    print(Dataset['Fixed Income Fund'][1])  # 但是如果没有该key值,就会报错

    Financial Notes

    print(Dataset.get("Alternative Investment"))  #Get不会报错,呈现none
    print(Dataset.get("Fixed Income Fund"))

    None
    ['Government bond', 'Financial Notes', 'Credit Bond', 'MBS']

    其他内建函数

    • 打印value和key值,返回一个list
    print(Dataset.values())  # values: 全部values以list方式打印

    dict_values(['Deep value', 'Market oriented with a growth bias', ['Government bond', 'Financial Notes', 'Credit Bond', 'MBS']])

    print(Dataset.keys())    # keys:list打印所有key值

    dict_keys(['Equity Fund', 'Balanced Fund', 'Fixed Income Fund'])

    • setdault
    print(Dataset.setdefault('Equity Fund','Fundamental Growth'))    # 如果字典中 存在键值对 则不变  没有则创建 创建键值对的时候 取dictionary.setdefault里的值

    Deep value

    • 合并两个dictionaries
    Dataset2 = {'updated method': ['QFII','RQFII']}
    
    Dataset2.update(Dataset)   #将dataset合并到dataset2里面去
    print(Dataset2)
    •  items: 返回一个list
    print(Dataset.items())

    dict_items([('Equity Fund', 'Deep value'), ('Balanced Fund', 'Market oriented with a growth bias'), ('Fixed Income Fund', ['Government bond', 'Financial Notes', 'Credit Bond', 'MBS'])])

    • clear:删除所有元素
    • copy: 浅copy

    循环Dictionary

    #方法1:推荐方式,直接取出
    for i in sorted(Dictionary1):  # sorted 返回一个有序的迭代子
        print(i,Dictionary1[i])
    
    #方法2:items后转成list,数据量如果很大,就非常麻烦
    for k,v in Dictionary1.items():
        print(k,v)

    其他函数 - len():

    返回所有元素(KEY-VALUE)的数目

  • 相关阅读:
    在java中获取URL的域名或IP与端口
    解决notepad++64位没有plugin manager的问题
    统一认证需要解决的问题
    搭建Maven私服
    Update openssh7.9 on centos6
    python下载想听的有声书,让喜马拉雅收费,我是程序员!
    golang ---获取内存信息
    websocket学习
    go 读取BMP文件头二进制读取
    go 计算文件行
  • 原文地址:https://www.cnblogs.com/lg100lg100/p/7082239.html
Copyright © 2020-2023  润新知