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
    

 

posted @ 2017-11-29 20:25  丁头零零  阅读(159)  评论(0编辑  收藏  举报