python5-字典

1、字典:一系列的键-值对。

      可以使用键来访问与之相连的值。与键相关联的值可以是数字、字符串、列表及字典。

      格式:字典名={'键1':'值1','键2':'值2'……}

  1)访问字典的值: 字典名['键']

1 alien={'color':'green','points':5}
2 new_point=alien['points]
3 print('You just earned '+str(new_point)+' points!')

  2)添加键-值对

1 alien={'color':'green','points':5}
2 print(alien)
3 alien[x_position]=0
4 alien[y_position]=25
5 print(alien)

  3)修改字典中的值:指定字典名,用方括号括起的键及与键相关联的新值

1 alien={'color':'green'}
2 print('The alient is '+alient['color']+'.')
3 alient['color']='red'
4 print('The alien is now '+alien['color']+'.')

  4)删除键-值对: del 字典名['键']  (不可恢复)

1 alien={'color':'green','points':5}
2 print(alien)
3 del alien['color']
4 print(alien)

  5)由类似对象组成的字典:用字典存众多对象的同一种信息

  6)遍历字典

    * 遍历所有的键-值对: for  键别名,值名  in  字典名.item()方法

      - item()方法:返回一个键-值对列表;

      - 即使遍历字典时,键-值对的返回顺序与存储顺序不同,python只跟踪键值之间的关联关系;

      - 字典可存储很多数据,使用for循环可以轻易将其显示出来;

1 user={
2   'name':'ann',
3   'age':18,
4   'city':'anhui'  
5 }
6 for k,v in user.item():
7     print('
Key:'+k)
8     print('
Value:'+v)

    * 遍历字典中的所有键: keys()方法,返回一个列表

1 languages={
2   'jen':'C',
3   'Bob':'Python',  
4 }
5 for language in languages:  /   for language in languages.keys():
6     print(language.title())

    * 按顺序遍历字典中的所有键

      a. 在for循环中对返回的键及进行排序;

      b. 使用函数sorted()获得特定顺序排列的键列表的副本;

favorite_language={
  'jen':'C',
  'Bob':'Python'    
}
for name in sorted(favorite_language.key()):
    print(name.title()+',thank you for taking the poll.')

    * 遍历字典中的所有值:value()方法,返回一个值列表,不含键。

      - set(): 集合,类似于列表,但每个元素必须是独一无二的;

1 language={
2   'jen':'C',
3   'Bob':'Python'  
4 }
5 for language in set(languages.value()):
6     print(language.title())

  7)嵌套:有时要将一系列字典嵌在列表中,或将列表作为值存在字典中,即“嵌套”。

    * 字典列表

1 alien_0={'color':'red','points':1}
2 alien_1={'color':'blue','points':2}
3 alien_2={'color':'yellow','points':3}
4 aliens=[alien_0,alien_1,alien_2]
5 for alien in aliens:
6     print(alien)

    * 字典中存列表

    * 在字典中存储字典

原文地址:https://www.cnblogs.com/Free-Ink/p/12601391.html