本文主要是介绍chapter6 字典,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- Python中,字典放在花括号{}中的一系列键-值对表示
- 获取与键相关的值,依次指定字典名和放在花括号内的键
- del语句将相应的键-值对彻底删除
- 遍历所有的键-值对
user_0 ={'username':'efermi','first':'enrico','last':'fermi',
}for key,value in user_0.items()://编写用于遍历字典的for循环,声明两个变量,用于存储键-值对中的键和值print("\nKey: "+ key)print("Value:"+ value)
---------------------------------------------------------------------
Key: username
Value:efermiKey: first
Value:enricoKey: last
Value:fermi
- 遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys()://方法key()print(name.title())
------------------------------------------------------
Jen
Sarah
Edward
Phil
- 按顺序遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):print(name.title())
---------------------------------------------------
Edward
Jen
Phil
Sarah
-遍历字典所有值
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}for language in set(favorite_languages.values()):#values()遍历字典所有值 对包含重复列表调用set()print(language.title())
-------------------------------------------------------------
C
Ruby
Python
-在字典中存储字典
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())
---------------------------------------------------------------------------
Username: aeinsteinFull name: Albert EinsteinLocation: PrincetonUsername: mcurieFull name: Marie CurieLocation: Paris
课后习题
message = {'first_name':'Lily','last_name':'Z','age':'22','city':'HangZhou'}
print(message['first_name'])
print(message['last_name'])
print(message['age'])
print(message['city'])
--------------------------------------------------------------------------
Lily
Z
22
HangZhou
favorite_num = {'a':'1','b':'2','c':'3','d':'4','e':'5'}
print("a favorite number is "+favorite_num['a']+".")
print("b favorite number is "+favorite_num['b']+".")
print("c favorite number is "+favorite_num['c']+".")
print("d favorite number is "+favorite_num['d']+".")
print("e favorite number is "+favorite_num['e']+".")
-------------------------------------------------------------
a favorite number is 1.
b favorite number is 2.
c favorite number is 3.
d favorite number is 4.
e favorite number is 5.
glossary = {'string':'A series of characters.','comment':'A nnote in a program that the Python interpreter ignores.','list':'A collectio of items in a particular order.','loop':'Work through a collection of items,one at a time.','dictionary':'A collection of Key-value pairs.',
}word = 'string'
print("\n"+word.title()+": "+glossary[word])word = 'comment'
print("\n"+word.title()+": "+glossary[word])word = 'list'
print("\n"+word.title()+": "+glossary[word])word = 'loop'
print("\n"+word.title()+": "+glossary[word])word = 'dictionary'
print("\n"+word.title()+": "+glossary[word])
----------------------------------------------------------------------
String: A series of characters.Comment: A nnote in a program that the Python interpreter ignores.List: A collectio of items in a particular order.Loop: Work through a collection of items,one at a time.
glossary = {'string':'A series of characters.','comment':'A nnote in a program that the Python interpreter ignores.','list':'A collectio of items in a particular order.','loop':'Work through a collection of items,one at a time.','dictionary':'A collection of Key-value pairs.',
}
for word , definition in glossary.items():print("\n"+ word.title()+":"+definition)--------------------------------------------------------------------------String:A series of characters.Comment:A nnote in a program that the Python interpreter ignores.List:A collectio of items in a particular order.Loop:Work through a collection of items,one at a time.Dictionary:A collection of Key-value pairs.
rivers = {'nile':'rgypt','mississippi':'Us','fraser':'Canada','yangtze':'China',
}for river,country in rivers.items():print("The "+river.title()+" flowa through "+country.title()+".")print("\n The following rivers are included in this data set:")
for river in rivers.keys():print("- "+river.title())
--------------------------------------------------------------------------
The Nile flowa through Rgypt.
The Mississippi flowa through Us.
The Fraser flowa through Canada.
The Yangtze flowa through China.The following rivers are included in this data set:
- Nile
- Mississippi
- Fraser
- Yangtze
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():print(name.title() + "'s favorite language is " +language.title() + ".")names = ['jen','sarah','ben','lily']
for name in names:if name in favorite_languages.keys():print("thank u,"+name.title()+"!")else:print("weclome,"+name.title()+"!")
----------------------------------------------------------
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.
thank u,Jen!
thank u,Sarah!
weclome,Ben!
weclome,Lily!
message_01 = {'first_name':'Lily','last_name':'Z','age':'22','city':'HangZhou'}
message_02 = {'first_name':'Ben','last_name':'S','age':'10','city':'ShenZhen'}
message_03 = {'first_name':'Cat','last_name':'F','age':'30','city':'BeiJin'}peoples = [message_01,message_02,message_03]for people in peoples:print(people)
-----------------------------------------------------------------------------------------
{'first_name': 'Lily', 'last_name': 'Z', 'age': '22', 'city': 'HangZhou'}
{'first_name': 'Ben', 'last_name': 'S', 'age': '10', 'city': 'ShenZhen'}
{'first_name': 'Cat', 'last_name': 'F', 'age': '30', 'city': 'BeiJin'}
#Make an empty ;ist to store the pets in.
pets = []#Make individual pets, and store each one on the list.
pet = {'animal type':'python','name':'john','owner':'guido','eats':'bugs',
}
pets.append(pet)pet = {'animal type':'chicken','name':'ben','owner':'tiffy','eats':'seeds',
}
pets.append(pet)pet = {'animal type':'dog','name':'peo','owner':'eric','weight':37,'eats':'shoes',
}
pets.append(pet)#dispaly information about each pet
for pet in pets:print("\nHere's what I know about "+pet['name'].title()+":")for key,value in pet.items():print("\t"+key+":"+str(value))
-------------------------------------------------------------------------------
Here's what I know about John:animal type:pythonname:johnowner:guidoeats:bugsHere's what I know about Ben:animal type:chickenname:benowner:tiffyeats:seedsHere's what I know about Peo:animal type:dogname:peoowner:ericweight:37eats:shoes
favorite_places = {'eric':['bear mountain','death valley','tierra del fuego'],'erin':['hawaii','iceland'],'ever':['mt.verstovavua','the playfround','south carolina']
}for name,places in favorite_places.items():print("\n"+name.title()+" likes the following places:")for place in places:print("-"+place.title())
---------------------------------------------------------------
Eric likes the following places:
-Bear Mountain
-Death Valley
-Tierra Del FuegoErin likes the following places:
-Hawaii
-IcelandEver likes the following places:
-Mt.Verstovavua
-The Playfround
-South Carolina
favorite_numbers = {'mandy':[42,17],'micah':[23,33,44],'gus':[3,4],
}for name,numbers in favorite_numbers.items():print("\n"+name.title()+" likes the following numbers:")for number in numbers:print(" "+str(number))
-----------------------------------------------------------------------Mandy likes the following numbers:4217Micah likes the following numbers:233344Gus likes the following numbers:34
cities = {'santiago':{'country':'chile','population':33333333,'nearby mountains':'andes',},'talkrren':{'country':'aksd','population':4535432445,'nearby mountains':'skjdjd',},'hausdueh':{'country':'dsdsf','populartion':3423544543,'nearby mountains':'fdsfsd',},
}for city ,city_info in cities.items():country = city_info['country'].title()population = city_info['country'].title()mountains = city_info['nearby mountains'].title()print("\n"+city.title()+" is in "+country +".")print(" it has a population of about "+str(population)+".")print("The "+mountains+"mountains are nearby.")
-----------------------------------------------------------------------
Santiago is in Chile.it has a population of about Chile.
The Andesmountains are nearby.Talkrren is in Aksd.it has a population of about Aksd.
The Skjdjdmountains are nearby.Hausdueh is in Dsdsf.it has a population of about Dsdsf.
The Fdsfsdmountains are nearby.
这篇关于chapter6 字典的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!