python学习笔记

python10-查啊查啊查字典

2015-12-21  本文已影响118人  yigoh
python

之前我们说到列表这个东西,觉得有了它,什么都很轻松,但是。。。
它貌似做不到会英语就能懂(python一大卖点)——恐怕多少还得要求会点数学吧?
于是,仿生学(大雾。。。)力作,字典横空出世,如其小名散列表显示得那样,字典就是打散了的(没有顺序的)列表

接下来,让我们在py环境里看看字典的用法吧:
用大括号{}表示一个字典,关键词和解释用冒号隔开,每个词条用逗号隔开:

dict = {"banana" : "a long curved fruit with a thick yellow skin and soft flesh, that grows on trees in hot countries",
    "apple" : "a round fruit with shiny red or green skin and firm white flesh",
    "orange" : "a round citrus fruit with thick reddish-yellow skin and a lot of sweet juice"}

字典变量名[关键词]的形式进行查询:

dict["apple"] # 用起来就相当于一个内容为相应解释的变量

想把“水果字典”变成“公司字典”要怎么办呢?

# 首先要修改“apple”的解释(和列表很相似吧~)
dict["apple"] = "a technology company"

# 其次要删除“banana”和“orange”(应该没有公司叫这俩名字吧?)
del dict["banana"] # "del"就是“delete”的缩写,都认识吧
del dict["orange"]

# 那么,想一口气清空字典,要如何做到?
dict.clear() # 这样就行了,不过此时最好别写它

# 最后,要添上几个公司
dict["baidu"] = "a rascal company”# 直接加上就可以了,相当方便
dict["tencent"] = "another rascal company"

利用循环,来打印出整个字典吧!

for key in dict:
   print("%s : %s" % (key, dict[key])) # 格式化字符串还记得吧?这是一个字符串里有多个占位符的使用格式~

字典中的关键词(数字、字符串、变量)和解释(只要是表达式就行)可以是多种多样的:

dict[1] = dict

a = 98 + 3

lll = [2, "d", "aaa"]

dict[a] = lll

只需注意:关键词不可重复!

有任何问题请回复提出。然后欢迎关注微信公众号格物致愚

格物致愚
上一篇下一篇

猜你喜欢

热点阅读