• python之字典操作


    字典是python语言中唯一的映射类型.

    # -*- coding: cp936 -*-
    # dict examples
    
    # 创建字典
    dict1 = {}
    dict2 = {'name':'earth', 'port':80}
    fdict = dict((['x',1],['y',2]))
    
    # 访问字典的值
    # 1. 遍历
    for key in dict2:
        print 'key=%s, value=%s' %(key, dict2[key])
    # 2. 修改
    dict2['name'] = 'moon'
    
    # 检查是否存在对应的键
    # 1. in
    if 'name' in dict2:
        print dict2['name']
    # 2. has_key()
    if dict2.has_key('test') == True:
        print dict2['test']
    else:
        print 'dict2 has not the value of \'test\''
    
    # 增加元素
    dict2['address'] = 'china'  # 若不存在对应key,则增加元素
    
    # 删除元素
    print dict2.pop('name')   #删除并返回键为'name'的条目
    del dict2['address']
    dict2.clear()   # 删除dict2中所有条目,dict2变成空字典
    print dict2
    del dict2       # 删除字典,字典不再存在
    
    
  • 相关阅读:
    ubuntu安装软件失败
    阶乘函数 注意事项
    汇编退出
    vim比较文件
    汇编调试
    Redis
    记录一次ajax使用
    oracle11g导出dmp文件时不能导出空表,导致缺表
    将小数点后的0去掉
    redis
  • 原文地址:https://www.cnblogs.com/wangzhijun/p/2956338.html
Copyright © 2020-2023  润新知