天天看點

chapter6 字典

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:efermi

Key: first
Value:enrico

Key: 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: aeinstein
	Full name: Albert Einstein
	Location: Princeton

Username: mcurie
	Full name: Marie Curie
	Location: Paris
           

課後習題

chapter6 字典
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

           
chapter6 字典
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.
           
chapter6 字典
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.

           
chapter6 字典
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.

           
chapter6 字典
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
           
chapter6 字典
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!

           
chapter6 字典
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'}
           
chapter6 字典
#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:python
	name:john
	owner:guido
	eats:bugs

Here's what I know about Ben:
	animal type:chicken
	name:ben
	owner:tiffy
	eats:seeds

Here's what I know about Peo:
	animal type:dog
	name:peo
	owner:eric
	weight:37
	eats:shoes
           
chapter6 字典
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 Fuego

Erin likes the following places:
-Hawaii
-Iceland

Ever likes the following places:
-Mt.Verstovavua
-The Playfround
-South Carolina
           
chapter6 字典
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:
 42
 17

Micah likes the following numbers:
 23
 33
 44

Gus likes the following numbers:
 3
 4

           
chapter6 字典
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 字典