Python-字典

1、字典操作

1、字典是一系列键—值对。每个键都与一个值相关联,你可以使用键来访问与之 相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典,可将任何Python对 象用作字典中的值

‘color’是一个键,与之相关联的值为’green’

alien_0 = {'color': 'green'} 

2、访问字典中的值
要获取与键相关联的值,可依次指定字典名和放在方括号内的键

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

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, 'y_position': 25, 'x_position': 0} 

键—值对的排列顺序与添加顺序不同。Python不关心键—值对的添加顺序, 而只关心键和值之间的关联关系。

3、在空字典中添加键—值对是为了方便,而有时候必须这样做。为此,可先使用一对 空的花括号定义一个字典,再分行添加各个键—值对。

alien_0 = {} 
alien_0['color'] = 'green' 
alien_0['points'] = 5 

4、修改字典中的值
要修改字典中的值,可依次指定字典名、用方括号括起的键以及与该键相关联的新值

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. 

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

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

2、遍历字典

1、遍历所有的键—值对
如果要获悉该用户字典中的 所有信息,该怎么办呢?可以使用一个for循环来遍历这个字典

user_0 = {
    'username': 'efermi', 
    'first': 'enrico', 
    'last': 'fermi', 
    }
    
for key, value in user_0.items(): 
   print("\nKey: " + key) 
   print("Value: " + value) 
Key: last 
Value: fermi 

Key: first 
Value: enrico 

Key: username 
Value: efermi 

即便遍历字典时,键—值对的返回顺序也与存储顺序不同。Python不关心键—值对的存 储顺序,而只跟踪键和值之间的关联关系。

2、遍历字典中的所有键
在不需要使用字典中的值时,方法keys()很有用。
遍历字典时,会默认遍历所有的键,因此,如果将上述代码中的for name in favorite_ languages.keys():替换为for name in favorite_languages:,输出将不变。

favorite_languages = { 
  'jen': 'python', 
  'sarah': 'c', 
  'edward': 'ruby',  
  'phil': 'python', 
     } 
for name in favorite_languages.keys():         
    print(name.title()) 
Jen 
Sarah 
Phil 
Edward 

方法keys()并非只能用于遍历;实际上,它返回一个列表,其中包含字典中的所有键

3、遍历字典中的所有值 ,可使用方法values(),它返回一个值列表,而不包含 任何键。

3、嵌套

1、有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。你 可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。

2、字典列表

aliens = [] 
 for alien_number in range(30):
     new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} 
     aliens.append(new_alien) 
for alien in aliens[:5]:     
     print(alien) 
 print("...")
 print("Total number of aliens: " + str(len(aliens)))    
{'speed': 'slow', 'color': 'green', 'points': 5}  
{'speed': 'slow', 'color': 'green', 'points': 5}  
{'speed': 'slow', 'color': 'green', 'points': 5}  
{'speed': 'slow', 'color': 'green', 'points': 5}  
{'speed': 'slow', 'color': 'green', 'points': 5}  
... 
Total number of aliens: 30 

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 languages are:") 
for language in languages:        
   print("\t" + language.title()) 
Jen's favorite languages are:      
   Python      
   Ruby  
 
Sarah's favorite languages are:      
   C  
 
Phil's favorite languages are:      
   Python
   Haskell  
 
Edward's favorite languages are:      
   Ruby      
   Go 

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值