详细解析字典,learn python the hard way, 笨方法学python

#coding=utf-8

#create a mapping of provinces to suoxie
provinces = {
    'Guangdong': 'Yue',
    'Sichuan': 'Chuan',
    'Hainan': 'Qiong',
    'Fujian': 'Min',
    'Daiwan': 'Dai',
}

#create a basic set of provinces and some cities in them
cities = {
    'Yue': 'Guangzhou',
    'Chuan': 'Chongqin',
    'Qiong': 'Sanya',


}

#add some more cities

cities['Min'] = 'Fuzhou'
cities['Dai'] = 'Gaoxiong'

#print out some cities
print '-' * 10
print "Guangdong has:", cities['Yue']
print "Sichuan has:", cities['Chuan']

#print some provinces
print '-' * 10
print "Guangdong suoxie:", provinces['Guangdong']
print "Sichuan suoxie:", provinces['Sichuan']

#do it by using the provinces then cities dict
print '_' * 10
print " Hainan has : ", cities[provinces['Hainan']]
print "Daiwan has: ", cities[provinces['Daiwan']]

#print every provinces suoxie
print '-' * 10
for province, suoxie in provinces.items(): 
    print "%s is %s" % (province, suoxie)

#print every city in provinces
print '-' * 10
for suoxie, city in cities.items():
    print "%s has the city %s" % (suoxie, city)

#now do both  at the same time
print '-' * 10
for x, y in provinces.items():
    print "%s state is suoxie wei %s and has city %s" % (x, y, cities[y])
print '-' * 10
#safely get a suoxie by provinces that might not be there
province = provinces.get('Min', None)
if not province:
    print "Sorry, no Texas."


#get a city with a default value
city = cities.get('GUANG', 'guilin')
print "The city for the province 'Guang' is :%s" % city

print cities  #为什么这里打印整个字典,却没有'GUANG'的信息呢?为什么不是增加进去字典呢?而是一次性使用

for x, y in cities.items():  #如果没有使用items()函数,会提示too many values to umpack.
    print "This is our suoxie%s, and chengshi%s" % (x, y)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值