python编程基础(五):字典

区别一下  列表、元组、字典的形式

列表:  列表名 = [  ]    # 注意列表用中括号

元组:  元组名 = (  )   # 注意元组用小括号

字典: 字典名 =  {  }   #注意字典用花括号

一、使用字典

1、字典用 花括号 括起来,并且使用“键-值”的形式

alien_0 = {'color':'green','points':5}

print(alien_0['color'])
print(alien_0['points'])


结果:
green
5

2、添加 键-值 对

字典是一种动态的结构,可以随时添加 键-值  对,添加方式是,直接对字典定义 键及对应的值

alien_0 = {'color':'green','points':5}

print(alien_0)

alien_0['x_position'] = 0
alien_0['y_position'] = 25

print(alien_0)



结果:
{'points': 5, 'color': 'green'}
{'points': 5, 'color': 'green', 'y_position': 25, 'x_position': 0}

可以发现,定义的顺序和在字典中存储的顺序是不一样的,因为字典只在意的是 键与值之间的对应关系。

3、修改字典中的值

直接修改对应键的值即可

4、删除 键-值 对      del语句

alien_0 = {'color':'green','points':5}

print(alien_0)

del alien_0['points']

print(alien_0)


结果:
{'points': 5, 'color': 'green'}
{'color': 'green'}

二、遍历字典

1、遍历所有的  键-值  对     .items() 语句

使用   .items() 返回的是一个由 键-值  组成的列表。注意,在遍历所有的  键-值  的时候,用于 for  的变量名最好是代表着字典中元素的意义的,如下:

1、 例1
user_0 = {
          'username':'efermi',
          'frist':'enrico',
          'last':'fermi'}
          
          
for key, value in user_0.items():
    print('\nKey:' + key)
    print('Value:' + value)
    


结果:
Key:frist
Value:enrico

Key:username
Value:efermi

Key:last
Value:fermi



2、 例2
    
favorite_languages={
                    'jen':'python',
                    'sarah':'c',
                    'edward':'ruby',
                    'phil':'python',
                    'chen':'c++'}
                    
                    
for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " + 
          language + '.')


结果:
Chen's favorite language is c++.
Phil's favorite language is python.
Jen's favorite language is python.
Edward's favorite language is ruby.
Sarah's favorite language is c.

由于例2中的字典表示的是 每个人所喜欢的编程语言,所以键 可以表示为name,值可以用 language 表示。

2、遍历所有的  键       .keys()

favorite_languages={
                    'jen':'python',
                    'sarah':'c',
                    'edward':'ruby',
                    'phil':'python',
                    'chen':'c++'}
                    
                    
for name in favorite_languages.keys():
    print(name.title())


结果:
Chen
Phil
Jen
Edward
Sarah

3、遍历所有的  值       .values()

favorite_languages={
                    'jen':'python',
                    'sarah':'c',
                    'edward':'ruby',
                    'phil':'python',
                    'chen':'c++'}
                    
                    
for language in favorite_languages.values():
    print(language.title())


结果:
C++
Python
Python
Ruby
C

可以发现,如果是直接将 值取出来的话,可能有很多的重复内容,因为键一般情况下不会有重复,但是值会有,如果我们想剔除值中重复的项,可以使用 set() 语句来实现:

favorite_languages={
                    'jen':'python',
                    'sarah':'c',
                    'edward':'ruby',
                    'phil':'python',
                    'chen':'c++'}
                    
                    
for language in set(favorite_languages.values()):
    print(language.title())


结果:
C
Ruby
Python
C++

注意:for language in set(favorite_languages.values())  

set 加在 字典.values()  前面

三、嵌套

嵌套分为三种: 字典列表(列表中的元素是字典),列表字典(字典中键的值是列表),字典嵌套(字典中键的值是字典)

1、字典列表

alien_0 = {'color':'green','points':5}
alien_1 = {'color':'yellow','points':10}
alien_2 = {'color':'red','points':15}

aliens = [alien_0,alien_1,alien_2]

for alien in aliens:
    print(alien)


结果:
{'points': 5, 'color': 'green'}
{'points': 10, 'color': 'yellow'}
{'points': 15, 'color': 'red'}

2、列表字典

favorite_languages={
                    'jen':['python','c'],
                    'sarah':['c','c++'],
                    'edward':['ruby','matlab'],
                    'phil':['python','c#']}
                    
                    
for name, languages in favorite_languages.items():
    print(name.title() + "'s favorite language are:")
    for language in languages:
        print('\t' + language.title())



结果:
Phil's favorite language are:
        Python
        C#
Jen's favorite language are:
        Python
        C
Edward's favorite language are:
        Ruby
        Matlab
Sarah's favorite language are:
        C
        C++

3、字典嵌套

users = {
         'aeinstein':{
                      'frist':'albert',
                      'last':'einstein',
                      'location':'china',
                      },
                      
          'mcurie':{
                    'frist':'marie',
                    'last':'curie',
                    'location':'paris',
                    },
        }
        
for use_name,user_info in users.items():
    print('\n Username:' + use_name.title())
    full_name = user_info['frist'] + ' ' + user_info['last']
    location = user_info['location']

    print('\t Full name:' + full_name.title())
    print('\t Location:' + location.title())



结果:
 Username:Mcurie
         Full name:Marie Curie
         Location:Paris

 Username:Aeinstein
         Full name:Albert Einstein
         Location:China

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章