#遍历字典(●'◡'●)##1 遍历所有的键值对
user_0={"username":"efermi","first":"enrico","last":"fermi",}for k,v in user_0.items():print("\nKey:"+k)print("Value:"+v)#2 遍历字典中的所有键
user_0={"username":"efermi","first":"enrico","last":"fermi",}
friends=["fermi","phil"]for name in user_0.keys():print(name.title())if name in friends:print("Hi")#2.5 按顺序遍历字典中的所有键
user_0={"username":"efermi","first":"enrico","last":"fermi",}for k insorted(user_0.keys()):print(k.title()+",thank you for taking the poll.")#3 遍历字典中的所有值
user_0={"username":"efermi","first":"enrico","last":"fermi",}for v in user_0.values():print(v.title())#利用set()可以使每一项都是独一无二for v inset(user_0.values()):print(v.title())#动手414
river={"nile":"egypt","b":"bc","j":"jk"}for name,place in river.items():print("The "+name.title()+"runs through "+place.title()+".")for name in river.keys():print(name)for place in river.values():print(place)
name=["kk","ll","mm"]
name_0={"n1":"kk","n2":"oo","n3":"uu"}for n in name_0.values():if n in name:print("HI")else:print("bye")
嵌套
#嵌套:字典存储在列表中或者将列表作为值存储在字典中。#1 字典列表
name_1={"color":"red","points":9}
name_2={"color":"blue","points":11}
name_3={"color":"black","points":88}
names=[name_1,name_2,name_3]for name in names:print(name)#用range生成30个相同名字
names=[]for name_number inrange(30):
new_name={"color":"red","points":9}
names.append(new_name)for name in names[:5]:print(name)print("...")#修改for name in names[0:3]:if name["color"]=="red":
name["color"]="yellow"
name["speed"]="medium"
name["points"]=10for name in names[:5]:print(name)print("...")#2 在字典中存储列表
pizza={"crust":"thick","toppings":["mushrooms","extra cheese"],}print("You ordered a"+pizza["crust"]+"-crust pizza"+"with the following toppings:")for topping in pizza["toppings"]:print("\t"+topping)
fav_languages={"aad":["a","b"],"bbf":["c","d","e"],"ccg":["f","g","h","i"],}for name,languages in fav_languages.items():print("\n"+name.title()+"favorite languages are :")for language in languages:print("\t"+language.title())#3 在字典中存储字典
users={"aeinstein":{"first":"albert","last":"einstein","location":"princeton",},"mcurie":{"first":"marie","last":"curie","location":"paris",},}for username,user_info in users.items():print("\nUsername:"+username)
full_name=user_info["first"]+" "+user_info["last"]
location=user_info["location"]print("\tFull name:"+full_name.title())print("\tLocation:"+location.title())