Chapter6笔记(字典)

1使用字典

  • 字典 是一系列键—值对
  • 修改字典的值
    #代码
    alien_0 = {'color': 'green'}
    print("The alien is " + alien_0['color'] + ".")
    alien_0['color'] = 'yellow'
    print("The alien is now " + alien_0['color'] + ".")
    
    #结果
    The alien is green.
    The alien is now yellow.
  • 删除键值对,使用del
    #代码
    alien_0 = {'color': 'green', 'points': 5}
    print(alien_0)
    del alien_0['points']
    
    #结果
    {'color': 'green', 'points': 5}
    {'color': 'green'}

    动手试一试:

  • 6-1 人:使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。该字典应包含键first_name 、last_name 、age 和city 。将存储在该字典中的每项信息都打印出来

    #代码
    a_person={'first_name':'july','last_name':'pig' ,'age':17,
              'city':'newzeland'}
    print("the person'name is "+a_person['first_name']+", the person'last_name is "
          +a_person['last_name']+", the person'age is "+str(a_person['age'])+
          ", the person'city is "+a_person['city'])
    
    #结果
    the person'name is july, the person'last_name is pig, the person'age is 17, the person'city is newzeland

    2遍历字典

  • 遍历所有键值对  for key, value in user_0.items():    #这里的key和value可以换成其他单词,顺序正确即可

  • 遍历字典中的所有键 for name in favorite_languages.keys():   #这里的name可以换成其他单词,顺序正确即可

    #代码
    user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
    }
    for key, value in user_0.items(): 
        print("\nKey: " + key) 
        print("Value: " + value)
    print('\n')
    for name in user_0.keys():
        print(name.title())
    #结果
    Key: username
    Value: efermi
    
    Key: first
    Value: enrico
    
    Key: last
    Value: fermi
    
    
    Username
    First
    Last
    
    

     

  • 可使用当前键来访问与之相关联的值    if name in friends:
  • 函数sorted()按顺序显示了所有被调查者的名字
    favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
    friends = ['phil', 'sarah']
    #代码1
    for name in favorite_languages.keys():
        print(name.title())
        if name in friends:
            print(" Hi " + name.title() +
                ", I see your favorite language is " +
                favorite_languages[name].title() + "!")
    #代码2
    for name in sorted(favorite_languages.keys()):
    print(name.title() + ", thank you for taking the poll.")
    
    #结果1
    Edward
    Phil
    Hi Phil, I see your favorite language is Python!
    Sarah
    Hi Sarah, I see your favorite language is C!
    Jen
    #结果2
    Edward, thank you for taking the poll.
    Jen, thank you for taking the poll.
    Phil, thank you for taking the poll.
    Sarah, thank you for taking the poll.

     

  • 集合类似于列表,但每个元素必须独一无二的,set()函数

  • 方法values() ,它返回一个值列表

    favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
    print("The following languages have been mentioned:")
    for language in set(favorite_languages.values()):
        print(language.title())
    #结果:
    The following languages have been mentioned:
    Python
    C
    Ruby
    

    练习

  • 6-3Python字典可用于模拟现实生活中的字典,但为避免混淆,我们将后者称为词汇表。
    想出你在前面学过的5个编程词汇,将它们用作词汇表中的键,并将它们的含义作为值存储在词汇表中。
    以整洁的方式打印每个词汇及其含义。为此,你可以先打印词汇,在它后面加上一个冒号,再打印词汇的含义

  • print(key,':',value)

再在词汇表中添加5个Python术语。当你再次运行这个程序时,这些新术语及其含义将自动包含在输出中。

language={
    'python':'a language can py something',
    'c':'a language which can programe ef0ficient',
    'pythonss':'a language can py something',
    'cs': 'a language which can programe ef0ficient',
    'pythons':'a language can py something',
}
for key,value in language.items():
    print(key,':',value)
language['a']='a'
language['b']='b'
language['c']='c'
language['d']='d'
language['e']='e'
#结果
python : a language can py something
cc : a language which can programe ef0ficient
pythonss : a language can py something
cs : a language which can programe ef0ficient
pythons : a language can py something
a : a
b : b
c : c
d : d
e : e

6-5 河流 :创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键—值对可能是'nile': 'egypt' 。

  • 使用循环为每条河流打印一条消息,如“The Nileruns throughEgypt.”。
  • 使用循环将该字典中每条河流的名字都打印出来。
  • 使用循环将该字典包含的每个国家的名字都打印出来。
    rivers={
        'nile': 'egypt' ,
        'chang':'china',
        'meigong':'thailand',
    }
    for river,country in rivers.items():
        print('The ',river,'runs into ',country)
        print(river)
        print(country)
    #结果
    The  nile runs into  egypt
    nile
    egypt
    The  chang runs into  china
    chang
    china
    The  meigong runs into  thailand
    meigong
    thailand

    6-6调查:

  • 创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中。
    遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。

  • 对于还未参与调查的人,打印一条消息邀请他参与调查。

    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() + ".")
    checkmans={'lisa','jen','juli','phil'}
    for man in sorted(checkmans):
        if man in favorite_languages:
            print(man,', thanks for checking')
        else:
            print(man,', please accept checking')
    #结果
    Jen's favorite language is Python.
    Sarah's favorite language is C.
    Edward's favorite language is Ruby.
    Phil's favorite language is Python.
    jen , thanks for checking
    juli , please accept checking
    lisa , please accept checking
    phil , thanks for checking
    
    #6-7人:在为完成练习6-1而编写的程序中,再创建两个表示人的字典,
    #然后将这三个字典都存储在一个名为people 的列表中。遍历这个列表,
    #将其中每个人的所有信息都打印出来
    peoples={
        'a_person':{'first_name':'july',
                  'last_name':'pig' ,
                  'age':17,
                  'city':'newzeland',
                  },
        'b_person':{'first_name':'lyly',
                  'last_name':'haha' ,
                  'age':15,
                  'city':'thailand',
                  },
        'c_person':{'first_name':'wang',
                  'last_name':'helen' ,
                  'age':23,
                  'city':'china',
                  },
    }
    for person,info in peoples.items():
        print('person : ',person)
        name=info['first_name'] +' '+info['last_name']
        age=info['age']
        city=info['city']
        print('\tname :',name)
        print('\tage :', age)
        print('\tcity :', city)
    #结果
    person :  a_person
    	name : july pig
    	age : 17
    	city : newzeland
    person :  b_person
    	name : lyly haha
    	age : 15
    	city : thailand
    person :  c_person
    	name : wang helen
    	age : 23
    	city : china

     

    #6-8 宠物: :创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;
    # 在每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为pets 的列表中,
    # 再遍历该列表,并将宠物的所有信息都打印出来。
    mimi={'type':'cat','hostname':'LiLi'}
    wanwan={'type':'dog','hostname':'MeiMei'}
    dixi={'type':'skyline','hostname':'Sun'}
    pets=[mimi,wanwan,dixi]
    for pet in pets:
        for key,value in pet.items():
            print('%s:%s'%(key,value.title()))
    #结果
    type:Cat
    hostname:Lili
    type:Dog
    hostname:Meimei
    type:Skyline
    hostname:Sun
    

 

#6-9喜欢的地方 :创建一个名为favorite_places 的字典。在这个字典中,将三个人的名字用作键;
# 对于其中的每个人,都存储他喜欢的1~3个地方。为让这个练习更有趣些,
# 可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
favorite_places={
    '岚':['Russia','Tibet','America'],
    '琳':['Japan','France','Switzerland'],
    '选':['Australia','Italy','Thailand']
}
for key,value in favorite_places.items():
    if len(favorite_places)>0:
        print(key+"'s favorite place:")
        for val in value:
            print('\t'+val)
#结果
岚's favorite place:
	Russia
	Tibet
	America
琳's favorite place:
	Japan
	France
	Switzerland
选's favorite place:
	Australia
	Italy
	Thailand
#6-10喜欢的数字 :修改为完成练习6-2而编写的程序,让每个人都可以有多个喜欢的数字,
# 然后将每个人的名字及其喜欢的数字打印出来
favorite_nums= {
	'Nancy':[1,6,11],
	'Lucky':[2,7,12,17],
	'Handsome_Girl':[3,8,13],
	'Mary':[4,9,4,19,24,29],
	'Tony':[5,10,15,20,25,30,35,40],
}
for k,num in favorite_nums.items():
    if len(favorite_nums)>0:
        print(k+"'s favorite number: ")
        for n in num:
            print(' \t'+str(n))
#结果
Nancy's favorite number: 
 	1
 	6
 	11
Lucky's favorite number: 
 	2
 	7
 	12
 	17
Handsome_Girl's favorite number: 
 	3
 	8
 	13
Mary's favorite number: 
 	4
 	9
 	4
 	19
 	24
 	29
Tony's favorite number: 
 	5
 	10
 	15
 	20
 	25
 	30
 	35
 	4
#6-11 城市 :创建一个名为cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,
# 并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,
# 应包含country 、population 和fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
cities={
    'beijing':{
        'country':'China',
        'population':'2million',
        'fact':'the capital of China',
    },
    'Tokyo': {
        'country': 'Japan',
        'population': '3million',
        'fact': 'the capital of Japan',
    },
    'NewYork': {
        'country': 'America',
        'population': '4million',
        'fact': 'the capital of America',
    },
}
for city,information in cities.items():
    print(city+"'s information : ")
    for key1,value1 in information.items():
        print(key1,':',value1)
    print('\t')
#结果
beijing's information : 
country : China
population : 2million
fact : the capital of China
	
Tokyo's information : 
country : Japan
population : 3million
fact : the capital of Japan
	
NewYork's information : 
country : America
population : 4million
fact : the capital of America

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值