learn python the hard way(笨办法学python) 练习39

在练习39中,重点探讨了Python字典的使用,包括for循环遍历和get()方法。get()方法允许在键不存在时返回默认值,加深了对字典操作的理解。通过示例程序,展示了get()函数的实践应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

练习39中,我们主要学会了运用字典。

下面来介绍一下书中没有介绍到的知识点:

stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}
stuff字典中,‘name' 称为key(键),’Zed‘ 称为Value(值)。


本篇练习中,比较难理解的有以下几点:

1.dicts中,for循环的运用

for state, abbrev in states.items():
    print "%s is abbreviated %s" % (state, abbrev)
这段程序当中,for循环和以往学的不一样,原因是我们使用的是字典中每个单元由分别由key和value组成,如:

states = {
    'Oregon': 'OR',
    'Florida': 'FL',
    'California': 'CA',
    'New York': 'NY',
    'Michigan': 'MI'
}
所以,这里的for循环中的字符串需要两个变量来赋值,in后面也要变成states.item()



2.dict.get()的运用

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

dict.get(key, default=None)
  • key -- 字典中要查找的键。
  • default -- 如果指定键的值不存在时,返回该默认值值。

书中例题:

state = states.get('Texas')

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


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

可另写以下程序来认识dict.get()的运用:

state = states.get('Oregon')

if state:
    print "YES."
else:
    print "NO."

city = cities.get('CA', 'Does Not Exist')
print "The city for the state 'CA' is: %s" % city


我们也可以把这段程序写得更有趣一些:

print "Let's search the abbreviation of the state."
a = raw_input( "state's name:")
state = states.get(a)


if state:
    print "The %s 's abbrev is %s"% (a, state)
else:
    print "Sorry, cannot find this state."


# get a city with a default value
print "Let's search which city is in the state."
b = raw_input( "state's abbreviation:")
city = cities.get(b, 'Does Not Exist')
print "The city for the state '%s' is: %s" % (b, city)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值