Python学习笔记—字典

# _*_ coding:utf-8 _*_

##########字典############

#一个简单的字典

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

print(alien_0['color'])

print(alien_0['points'])

new_points = alien_0['points']

print("You just earned " + str(new_points) + " points!")

-------------------------------------------

green

5

You just earned 5 points!

-------------------------------------------

#添加键-值对

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}

-------------------------------------------

#先创建一个空字典

alien_0 = {}

alien_0['color'] = 'green'

alien_0['points'] = 5

print(alien_0)

-------------------------------------------

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

-------------------------------------------

#修改字典中的值

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

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.

-------------------------------------------

#一个例子:对一个能够以不同速度移动的外星人的位置进行追踪

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

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

#向右移动的外星人

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

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

x_increment = 1

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

x_increment = 2

else:

x_increment = 3

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

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

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

-------------------------------------------

Original x-position: 0

New x-position: 2

-------------------------------------------

#删除键-值对

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

print(alien_0)

del alien_0['points']

print(alien_0)

-------------------------------------------

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

{'color': 'green'}

-------------------------------------------

#遍历字典

user_0 = {

'username': 'efermi',

'first': 'enrico',

'last': 'fermi',

}

for key, value in user_0.items():

print(" Key: " + key)

print("Value: " + value)

-------------------------------------------


Key: username

Value: efermi


Key: first

Value: enrico


Key: last

Value: fermi

-------------------------------------------

#遍历字典中的所有键

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:

print(name.title())

-------------------------------------------

Jen

Sarah

Edward

Phil

-------------------------------------------

#可以用当前键来访问与之相关联的值

favorite_languages = {

'jen': 'Python',

'sarah': 'C',

'edward': 'Ruby',

'phil': 'Python',

}

friends = ['phil', 'sarah']

for name in favorite_languages.keys():

print(name.title())


if name in friends:

print(" Hi " + name.title() + ",I see your favorite language is " + favorite_languages[name].title() + "!")

-------------------------------------------

Jen

Sarah

Hi Sarah,I see your favorite language is C!

Edward

Phil

Hi Phil,I see your favorite language is Python!

-------------------------------------------

#方法keys()并非只能用于遍历;它返回一个列表

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

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

-------------------------------------------

Erin, please take our poll!

-------------------------------------------

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

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.

-------------------------------------------

#遍历字典中所有值

favorite_languages = {

'jen': 'Python',

'sarah': 'C',

'edward': 'Ruby',

'phil': 'Python',

}

print("The following languages have been mentioned:")

for language in favorite_languages.values():

print(language.title())

-------------------------------------------

The following languages have been mentioned:

Python

C

Ruby

Python

-------------------------------------------

#为剔除重复项,可使用集合(set)

print("The following languages have been mentioned:")

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

print(language.title())

-------------------------------------------

The following languages have been mentioned:

Python

Ruby

C

-------------------------------------------

#嵌套

#字典列表

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}

-------------------------------------------

#使用range()生成了30个外星人

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

aliens = []

#创建30个绿色的外星人

for alien_number in range(30):

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

aliens.append(new_alien)

#显示前5个外星人

for alien in aliens[:5]:

print(alien)

print("...")

#显示创建了多少个外星人

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

-------------------------------------------

{'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

-------------------------------------------

#使用for循环和if语句来修改某些外星人的颜色

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

aliens = []

#创建30个绿色的外星人

for alien_number in range(30):

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

aliens.append(new_alien)

for alien in aliens:

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

alien['color'] = 'yellow'

alien['speed'] = 'medium'

alien['points'] = 10

elif alien['color'] == 'yellow':

alien['color'] = 'red'

alien['speed'] = 'fast'

alien['points'] = 15


#显示前5个外星人

for alien in aliens[:5]:

print(alien)

print("...")

-------------------------------------------

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

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

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

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

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

...

-------------------------------------------

#在字典中存储列表

#存储所点披萨的信息

pizza = {

'crust': 'thick',

'toppings': ['mushrooms', 'extra cheese'],

}

#概述所点的披萨

print("You ordered a " + pizza['crust'] + "-crust pizza " + "with the following toppings:")

for topping in pizza['toppings']:

print(" " + topping)

-------------------------------------------

You ordered a thick-crust pizza with the following toppings:

mushrooms

extra cheese

-------------------------------------------

#每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表

favorite_languages = {

'jen': ['Python','Ruby'],

'sarah': ['C'],

'edward': ['Ruby', 'Go'],

'phil': ['Python', 'Haskell'],

}

for name, languages in favorite_languages.items():

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

for language in languages:

print(" " + 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

-------------------------------------------

#在字典中存储字典

users = {

'aeinstein': {

'first': 'albert',

'last': 'einstein',

'location': 'princeton',

},

'mcurie': {

'first': 'marie',

'last': 'curie',

'location': 'paris',

},

}

for username, user_info in users.items():

print(" Username: " + username)

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

location = user_info['location']


print(" Full name: " + full_name.title())

print(" Location: " + location.title())

-------------------------------------------

Username: aeinstein

Full name: Albert Einstein

Location: Princeton


Username: mcurie

Full name: Marie Curie

Location: Paris

-------------------------------------------

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章