#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)
详细解析字典,learn python the hard way, 笨方法学python
最新推荐文章于 2021-01-14 17:59:24 发布