第六章 字典

6.1 使用字典

  • 在Python中, 字典 是一系列键—值对 。 每个键 都与一个值相关联, 你可以使用键来访问与之相关联的值。 与键相关联的值可以是数字、 字符串、 列表乃至字典。 事实上, 可将任何Python对象用作字典中的值。
  • 在Python中, 字典用放在花括号{} 中的一系列键—值对表示
  • 添加键-值对:

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

02 print(alien_0)

03 alien_0['x_position'] = 0

04 alien_0['y_position'] = 25

05 print(alien_0)

>>>

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

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

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

6.2字典的操作

  • 字典在使用之前首先要先定义,可以通过创建空字典来实现字典的预定义

01 #1

02 alien_0 = {'color': 'green'}

03 print("The alien is " + alien_0['color'] + ".")

04 alien_0['color'] = 'yellow'

05 print("The alien is now " + alien_0['color'] + ".")

06

07 #2

08 alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}

09 print("Original x-position: " + str(alien_0['x_position']))

10 # 向右移动外星人

11 # 据外星人当前速度决定将其移动多远

12 if alien_0['speed'] == 'slow':

13 x_increment = 1

14 elif alien_0['speed'] == 'medium':

15 x_increment = 2

16 else:

17 # 这个外星人的速度一定很快

18 x_increment = 3

19 # 新位置等于老位置加上增量

20 alien_0['x_position'] = alien_0['x_position'] + x_increment

21 print("New x-position: " + str(alien_0['x_position']))

>>>

The alien is green.

The alien is now yellow.

Original x-position: 0

New x-position: 2

  • 字典的删除

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

  • 由类似对象组成字典

    字典存储的是一个对象的多种信息, 但你也可以使用字典来存储众多对象的同一种信息

01 favorite_language={

02 'jen':'Python',

03 'sarah':'c',

04 'edward':'Ruby',

05 'phil':'Python',

06 }

07 print("Sarah's favorite language is "+

08 favorite_language['sarah'].title()+

09 '.')

>>>

Sarah's favorite language is C.

6.3 字典的遍历

  • 利用方法items()遍历所有键-值对

01 favorite_languages={

02 'jen':'Python',

03 'sarah':'c',

04 'edward':'Ruby',

05 'phil':'Python',

06 }

07 for name,language in favorite_languages.items():

08 print(name.title()+"'sfavorite language is "+

09 language.title()+".")

>>>

Jen'sfavorite language is Python.

Sarah'sfavorite language is C.

Edward'sfavorite language is Ruby.

Phil'sfavorite language is Python.

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

01 favorite_languages={

02 'jen':'Python',

03 'sarah':'c',

04 'edward':'Ruby',

05 'phil':'Python',

06 }

07 for name in favorite_languages.keys():

08 print(name.title())

09

10 if 'erin' not in favorite_languages.keys():

11 print("Erin, please take our poll!")

>>>

Jen

Sarah

Edward

Phil

Erin, please take our poll!

  • 利用函数sorted()按照特定的顺序遍历字典中的所有

01 favorite_languages={

02 'jen':'Python',

03 'sarah':'c',

04 'edward':'Ruby',

05 'phil':'Python',

06 }

07 for name in sorted(favorite_languages.keys()):

08 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.

  • 利用方法values()遍历字典中的所有值
  • 利用函数set()创建非重复性列表——集合

01 favorite_languages={

02 'jen':'Python',

03 'sarah':'c',

04 'edward':'Ruby',

05 'phil':'Python',

06 }

07

08 # 利用方法values()遍历所有值

09 print("the following language have been mentioned:");

10 for language in favorite_languages.values():

11 print(language.title());

12

13 print("\n");

14 # 利用函数list()去掉列表中的重复性元素

15 for language in set(favorite_languages.values()):

16 print(language.title())

>>>

the following language have been mentioned:

Python

C

Ruby

Python

   

   

C

Python

Ruby

6.3 嵌套

  • 列表表之中存储字典

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

02 alien_1 = {'color': 'yellow', 'points': 10}

03 alien_2 = {'color': 'red', 'points': 15}

04 aliens = [alien_0, alien_1, alien_2]

05 for alien in aliens:

06 print(alien)

07

08 #创建一个用于存储外星人的空列表

09 aliens = []

10 # 创建30个绿色的外星人

11 for alien_number in range(30):

12 new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}

13 aliens.append(new_alien)

14 # 显示前五个外星人

15 for alien in aliens[:5]:

16 print(alien)

17 print("...")# 显示创建了多少个外星人

18 print("Total number of aliens: " + str(len(aliens)))

19

20 # try2

21 for alien in aliens[0:3]:

22 if alien['color'] == 'green':

23 alien['color'] = 'yellow'

24 alien['speed'] = 'medium'

25 alien['points'] = 10

26 # 显示前五个外星人

27 for alien in aliens[0:5]:

28 print(alien)

29 print("...")

>>>

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

{'color': 'yellow', 'points': 10}

{'color': 'red', 'points': 15}

{'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, 'speed': 'slow'}

...

Total number of aliens: 30

{'color': 'yellow', 'points': 10, 'speed': 'medium'}

{'color': 'yellow', 'points': 10, 'speed': 'medium'}

{'color': 'yellow', 'points': 10, 'speed': 'medium'}

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

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

...

  • 字典之中存储列表

01 favorite_languages = {

02 'jen': ['python', 'ruby'],

03 'sarah': ['c'],

04 'edward': ['ruby', 'go'],

05 'phil': ['python', 'haskell'],

06 }

07 for name, languages in favorite_languages.items():

08 print("\n" + name.title() + "'s favorite languages are:")

09 for language in languages:

10 print("\t" + language.title())

>>>

Jen's favorite languages are:

Python

Ruby

   

Sarah's favorite languages are:

C

   

Edward's favorite languages are:

Ruby

Go

   

Phil's favorite languages are:

Python

Haskell

  • 字典中存储字典

01 users = {

02 'aeinstein':

03 {

04 'first': 'albert',

05 'last': 'einstein',

06 'location': 'princeton',

07 },

08 'mcurie':

09 {

10 'first': 'marie',

11 'last': 'curie',

12 'location': 'paris',

13 },

14 }

15 for username, user_info in users.items():

16 print("\nUsername: " + username)

17 full_name = user_info['first'] + " " + user_info['last']

18 location = user_info['location']

19 print("\tFull name: " + full_name.title())

20 print("\tLocation: " + location.title())

>>>

Username: aeinstein

Full name: Albert Einstein

Location: Princeton

   

Username: mcurie

Full name: Marie Curie

Location: Paris

   

   

Practice:

01 cities={};

02 cities={

03 'Beijing':

04 {

05 'Contry':'China',

06 'population':'138,000',

07 'fact':'the biggest city in china',

08 },

09 'NewYork':

10 {

11 'Contry':'the U.S',

12 'population':'800,000',

13 'fact':'the capital of the U.S ',

14 },

15 'Tokyo':

16 {

17 'Contry':'Japan',

18 'population':'50,000',

19 'fact':'an island contry ',

20 },

21 };

22 for city,city_info in cities.items():

23 print(city);

24 for key,detail in city_info.items():

25 print("\t"+key+"\t"+detail);

>>>
 

Beijing

Contry        China

population        138,000

fact        the biggest city in china

NewYork

Contry        the U.S

population        800,000

fact        the capital of the U.S

Tokyo

Contry        Japan

population        50,000

fact        an island contry

   

   

转载于:https://www.cnblogs.com/lovely-bones/p/10994572.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值