Python 字典的操作

#-*- coding:utf-8 -*-

people = {"name":"jack","age":18,"addr":"shanghai"}

#len()函数获取字典中键值对的个数

print(len(people))  #打印3

#keys()函数获取字典中键的集合
#在python2.x中获取的是列表,在python3.x获取的是一个对象

print(people.keys()) # python3.x打印 dict_keys(['name', 'age', 'addr'])

#values()函数类似
print(people.values())  #python3.x打印  dict_values(['jack', 18, 'shanghai'])

#items()函数返回的是字典的键值对集合
for tmp in people.items():
        print(tmp)   #打印每个键值对,键值对以元组的方式返回  ('name', 'jack')



#元组的拆包语法
num = (11,22)

a,b = num

print("a=%d b=%d"%(a,b))   #a=11 b=22


print("==================")

for m,n in people.items():
        print("key = %s ; value = %s"%(m,str(n)))

 

posted on 2018-06-25 20:28  寒魔影  阅读(119)  评论(0编辑  收藏  举报

导航