python 第4课 数据类型之dictionary

print("python字典是一系列键值对")
print("字典用花括号标识")
person1={'name':'小明','age':16}

print("访问字典值:")
print("我是"+person1['name'])
print("我今年"+str(person1['age'])+"岁了")

#print("添加字典键值对:")
person1['sex']='男'
person1['country']='China'
print(person1)

print("\n使用输入填充字典:")
responses={}
polling_active=True
while polling_active:
name=input("input your name:")
response=input("Which mountain would you like to climb someday?")
responses[name]=response
repeat=input("Would you like to let another person respond?(yes/ no):")
if repeat=="no":
polling_active=False
print("\n--- 'Poll Results ---")
for name,response in responses.items():
print(name+" would like to climb "+response+".")

#删除键值对
del person1['sex']
print(person1)

print("遍历字典:")
print("遍历字典所有键:")
for key in person1.keys():
print(key)
print("遍历字典所有值:")
for value in person1.values():
print(value)
print("遍历字典键值对(两种方法):")
for key,value in person1.items():
print(key+':'+str(value))
for key in person1.keys():
print(key+':'+str(person1[key]))
print("keys(),values(),items()都是返回一个列表")
print("values()返回列表可能包含重复项,可以利用set()函数去除重复项")
print("高级用法:字典,列表相互嵌套")

 

posted @ 2018-05-03 15:15  chuanzi  阅读(150)  评论(0编辑  收藏  举报