• ex39 字典


      字典的基本功能,增删改查,字典的item+for循环,以及如何保证在元素不存在的时候不出错。

    #-*- coding: UTF-8 -*-
    #create a mapping of state to abbreviation 
    states = {
        'Oregon': 'OR',
        'Florida': 'FL',
        'California': 'CA',
        'New York': 'NY',
        'Michigan': 'MI'
    }
    
    
    #creat a basic set of states and some cities in them."
    cities = {
        'CA': 'San Francisco',
        'MI': 'Detroit',
        'FL': 'Jacksonville'
    }
    
    
    #add some more cities
    cities['NY'] = 'New York'#添加
    cities['OR'] = 'Portland'
    
    #print out some cities
    
    print '-'*10
    print "NY state has:",cities['NY']#查找
    print "OR state has:",cities['OR']
    
    #print some states
    print '-' * 10
    print "Michigan's abbreviation is:",states['Michigan']
    print "Florida's abbreviation is:",states['Florida']
    
    #do it by using the state then cities dict
    print '-' * 10
    print "Michigan has:",cities[states['Michigan']]#这种情况,如果states里边那个不存在,那么是会报错的。但是呢如果用states.get()这就是正经查找不会报错了
    print "Florida has:",cities[states['Florida']]
    
    #print every state abbreviation
    print '-' * 10
    for state,abbrev in states.items():#items函数的功能
        print "%s is abbreviated %s" %(state,abbrev)
    
        
    #print every city in the state
    print '-' * 10
    for abbrev, city in cities.items():#通过items来实现比较直观,但是实际上该方法的内部原理是现将字典转化为列表,然后进行循环(虽然我也不明白),数据量大的时候,运算量会更大,
        print "%s has city %s" %(abbrev, city)
    #另外一种实现该功能的方法
    for i in cities:
        print "%s has city %s" %(i,cities[i])
    
    
        
    #now do both at the same time
    print '-' * 10
    for state,abbrev in states.items():
        print "%s state is abbreviated %s has city %s" %(state,abbrev,cities[abbrev])
        
    print '-' * 10
    #safely get a abbrevation by state that is not there
    state = states.get("Texas", None)#这个none不写应该也没事
    
    if not state: 
        print "Sorry,no Texas."
        
    #get a city with a defult value
    city = cities.get('TX', 'Does not exist.')
    print "The city for the state 'TX' is : %s " % city
        
  • 相关阅读:
    【6.29】数组和方法
    【6.28】判断和循环
    【6.27】两个数交换的4种方法
    NodeJS学习笔记
    准备使用马克飞象写博客
    前端基础
    学习笔记
    数据结构 — Java链表
    Java 日期类型与字符串的相互转换
    Scala(一)基础
  • 原文地址:https://www.cnblogs.com/dingtou00/p/7922532.html
Copyright © 2020-2023  润新知