Python:关于字典的相关操作

>>> people = {"Tom":170, "Jack":175, "Kite":160, "White":180}    #定义一个字典
>>> for name in people:      #获取value的值
 print people[name]

180
160
175
170
>>> for name in people:      #获取key的值
 print name

White
Kite
Jack
Tom
>>> people.keys()           # 获取所有key的值,和上面的for循环结果一样
['White', 'Kite', 'Jack', 'Tom']
>>> people.values()        # 获取所有value的值,和上面的for循环结果一样
[180, 160, 175, 170]
>>> people.has_key("White")       #判断字典中是否存在该键
True
>>> people["Tom"]          #通过key去获取value
170
>>> print [i for i in people if people.get(i) == 175]        #通过value去获取key,一句代码搞定
['Jack']
>>> print [i * 2 for i in people if people.get(i) == 175]      #让输出的值重复两次
['JackJack']
>>> print [(i + " ") * 2 for i in people if people.get(i) == 175 ]      #给重复的结果中间插入空格
['Jack Jack ']
>>> def test():
 print [i for i in people if people.get(i) == 175]       #把该代码定义成一个函数test()

>>> test()
['Jack']
>>> def test01(sg):                                             #把该代码定义为有参的函数test01()
 print [i for i in people if people.get(i) == sg]

>>> test01(175)
['Jack']

上一篇:MapReduce的输入输出格式


下一篇:Equal 和==比较