【Python基础知识】(五)字典及相关操作

时间:2020-07-11
本文章向大家介绍【Python基础知识】(五)字典及相关操作,主要包括【Python基础知识】(五)字典及相关操作使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

字典的概念

  Python中,字典是一系列键-值对Key-Value),每个键都与一个值相关联。这个值可以是数字、字符串、列表乃至字典。通过键可以访问与之相关联的值。

  在字典中,可以存储任意数量的键-值对。特别的,键-值对数量为0的字典被称作空字典

alien_0 = { 'color' : 'green', 'points' : 5 }
print( alien_0[ 'color' ] )
print( alien_0[ 'points' ] )

输出为:

green
5

对字典中键-值对的操作

1、访问字典中的值

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

new_points = alien_0[ 'points' ]
print( "You just earned " + str( new_points ) + " points!" )

 输出为:

You just earned 5 points!

2、添加键-值对

  字典是一种动态结构,可随时在其中添加键-值对。

alien_0 = { 'color' : 'green', 'points' : 5 }
print( alien_0 )

alien_0[ 'x_position' ) = 0
alien_0[ 'y_position' ) = 25
print( alien_0 )

 输出为:

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

  #注意:键-值对在字典中的排列顺序可能与添加顺序不同(如上述输出中新添加的两项位置互换),但特定键-值对之间的对应关系不会改变。

3、修改字典中的值

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.

4、删除键-值对

  使用del语句可将键-值对彻底删除。使用del语句时,必须指定字典名和要删除的

alien_0 = { 'color' : 'green', 'points' : 5 }
print( alien_0 )

del alien_0[ 'points' ]
print( alien_0 )

 输出为:

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

遍历字典

1、遍历所有键-值对

user_0 = {
    'username' : 'efermi' ,
    'first' : 'enrico' ,
    'last' : 'fermi' ,
    }

for key, value in user_0.items():    
    print( "\nKey: " + key )
    print( "Value: " + value )

 输出为:

Key: username
Value: efermi

Key: first
Value: enrico

Key: last
Value: fermi

  其中.items()是一个方法,使程序能够返回一个键-值对列表

  循环语句中的key,value(键,值)可替换为其他任意具有实际意义的参量,如name,language。

2、遍历所有键

  方法.keys()让Python提取字典favorite_languages中的所有,并依次将它们存储到变量name中。

favorite_languages = {
    'jen' : 'python' ,
    'sarah' : 'c' ,
    'edward' : 'ruby' ,
    'phil' : 'python' ,
    }

for name in favorite_languages.keys():
    print( name.title() )

输出为:

Jen
Sarah
Edward
Phil

  #注意:上述代码中,将循环语句变为"for name in favorite_languages:",即省略".keys()",输出将不变。这是因为当只给出一个参量时,Python默认优先遍历所有的。使用方法.keys()可让代码更好理解。

  使用函数sorted()可对for循环中返回的键排序,获得按特定顺序排列的键的副本

favorite_languages = {
    'jen' : 'python' ,
    'sarah' : 'c' ,
    'edward' : 'ruby' ,
    'phil' : 'python' ,
    }

for name in sorted( favorite_languages.keys() ):
    print( name.title() + ", thank you for taking the poll." )

输出为:

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.

3、遍历所有值

  方法.values()可让程序返回一个不包含任何键的值列表

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

输出为:

Python
C
Ruby
Python


C
Ruby
Python

  上述代码使用到了集合(set()),它能够暂时剔除列表中的重复项

嵌套

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 )

输出为:

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

2、在字典中存储列表

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

输出为:

Jen's favorite language(s) are:
        Python
        Ruby

Sarah's favorite language(s) are:
        C

Edward's favorite language(s) are:
        Ruby
        Go

Phil's favorite language(s) are:
        Python
        Haskell

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() )

输出为:

Username: aeinstein
        Full name: Albert Einstein
        Location: Princeton

Username: mcurie
        Full name: Marie Curie
        Location: Paris

参考书籍:《Python编程:从入门到实践》

2020-07-11

原文地址:https://www.cnblogs.com/carl39/p/13282846.html