您的位置:首页 > 编程语言 > Python开发

习题39 字典,可爱的字典

2016-07-30 15:33 411 查看
在之前,我们要在列表里面查询什么东西的时候,只能通过数字来查询

比如

things = ['a','b','c','d']
print things[1]
# b
things[1] = 'z'
print things[1]
# z
print things
# ['a','z','c','d']

而字典可以做的就是,让你通过任何东西来找到元素,不只是数字序数什么的了
比如

stuff = {'name':'Zed','age':36,'height':6*12+2}
print stuff['name']
# Zed
print stuff['age']
# 36
print stuff['height']
# 74
stuff['city'] = "San Francisco"
print stuff['city']
# San Francisco
# print stuff[1] is wrong
注意 stuff 是大括号!

以及

print stuff[1]会出错,应该是用了字典就不接受列表玩法了、、、

删除字典里的东西用 del

del stuff['city']
del stuff[1]
del stuff[2]
print stuff

======================================================================================================
接下来是源代码:

# creat a mapping of state to abbreviation(a shortened form of a word or phrase)
states= {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}

# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonviile'
}

# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Porland'

# 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']]
print "Florida has: ", cities[states['Florida']]

# print every state abbreviation
print '-' * 10
for state, abbrev in states.items():
print "%s has the city %s" % (state,abbrev)

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

# now do both at the same time
print '-' * 10
for state, abbrev in states.items():
print "%s state is abbreviated %s and has city %s" % (
state, abbrev, cities[abbrev])

print '-' * 10
# safely get a abbreviation by state that might not be there
state = states.get('Texas',None)

if not state:
print "Sorry, no Texas."

# get a city with a default value
city = cities.get('TX','Does Not Exist')
print "The city for the state 'TX' is: %s" % city

运行结果如下:



Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组

我没有明白的地方是 

for state, abbrev in states.items():
这句话 for 到底执行的是什么?

思考了一下,由于在 states 字典里面的格式是

{'state' : 'abbrev'}

所以 for 里面用的也是

for
state, abbrev in ...

这样的格式

Python
字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值

第二个问题: states.get('Texas',None) 有什么用?

语法是 dict.get(key, default=None)

key -- 字典中要查找的键。

default -- 如果指定键的值不存在时,返回该默认值

这里 key 就是 Texas,意思就是要查找它,然后找不到就返回None

相同的,后面从 cities 里面查找 TX ,没有,所以返回 Does Not Exits 到 city 里面

city = cities.get('TX','Does Not Exist')
====================================================================================================

附加练习:
2.
字典是无序的,我不知道怎么检查
但是网上说字典占内存,检索速度超级快
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python