zoukankan      html  css  js  c++  java
  • python字典 Dictionary

    #-*- coding:UTF-8 -*-
    
    tel={'jack':4098,'sape':4139}
    tel['guido']=4127
    
    print   tel
    #{'sape': 4139, 'jack': 4098, 'guido': 4127}
    
    print   tel['jack']
    #4098
    #如果key不存在会报错,避免key不存在的错误,有两种办法,一是通过in判断key是否存在
    print   'guido' in  tel     
    #True
    
    #二是通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value
    print  tel.get('jilk')
    print  tel.get('jilk',-1)
    #None
    #-1
    
    
    del tel['sape']
    tel['irv']=4127
    print  tel
    #{'jack': 4098, 'irv': 4127, 'guido': 4127}
    
    #要删除一个key,用pop(key)方法,对应的value也会从dict中删除
    tel.pop('irv')
    print  tel
    #{'jack': 4098, 'guido': 4127}
    
    print  tel.keys()
    #['jack', 'guido']
    
    
    
    #The dict() constructor builds dictionaries directly from sequences of key-value pairs:
    #dict() 函数用于创建一个字典。返回一个字典
    print   dict([('sape',4139),('guido',4127),('jack',4098)])   
    #{'sape': 4139, 'jack': 4098, 'guido': 4127}
    
    print {x:x**2 for x in  (2,4,6)}   
    #{2: 4, 4: 16, 6: 36}
    
    print  dict(sape=4139,guido=4127,jack=4098)
    #{'sape': 4139, 'jack': 4098, 'guido': 4127}
    
  • 相关阅读:
    struts2 显示表格
    设置eclipse默认编码为UTF-8 Set default encoding to utf-8 in eclipse
    java hibernate +mysql demo
    Java项目引入第三方Jar包
    mysql 常用sql
    C# snaps
    sql server 与mysql差异(innodb)
    系统数据监控
    Twitter Bootstrap Grid System
    设计模式之访问者模式
  • 原文地址:https://www.cnblogs.com/zwgblog/p/7170123.html
Copyright © 2011-2022 走看看