首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Python-字典

本节学习如何定义字典,以及如何使用存储在字典中的信息;如何访问和修改字典中的元素,以及如何遍历字典中的所有信息;如何遍历字典中所有的键-值对、所有的键和所有的值;如何在列表中嵌套字典、在字典中嵌套列表以及在字典中嵌套字典。

一点体会,Python的字典可以比较灵活的存储数据,比如可以将游戏用户的所有个人信息存储进一条字典,需要时通过for语句循环调出。唯一比较怀疑的是python处理大型数据的能力。

**************************** CODING *****************************

#CH6 字典

'''在Python中,字典用放在花括号{} 中的一系列键—值对表示'''

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

print(alien_0['color'])

new_points=alien_0['point']

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

'''添加键—值对'''

print(alien_0)

alien_0['x_position']=0

alien_0['y_position']=25

print(alien_0)

'''先创建一个空字典'''

alien_1={}

alien_1['color']='red'

alien_1['points']=20

print(alien_1)

'''修改字典中的值'''

alien_2={'color':'green'}

print(alien_2)

alien_2['color']='yellow'

print('\nthe alien is now ' + alien_2['color'] + '.')

'''来看一个更有趣的例子:对一个能够以不同速度移动的外星人的位置进行跟踪。为此,

我们将存储该外星人的当前速度,并据此确定该外星人将向右移动多远:'''

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

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

alien_0['speed']='fast'

# 向右移动外星人

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

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('\nNew x_position: ' + str(alien_0['x_position']) + '.\n')

'''删除键—值对'''

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

print(alien_0)

del alien_0['points']

print(alien_0)

'''6.3 遍历字典'''

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

'''获悉该用户字典中的所有信息'''

for k, v in user_0.items():

print('\nKey is ' + k)

print('Value is ' + v)

# 字典名.方法items(),它返回一个键—值对列表

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

'phil': 'python',}

for name, languages in favorite_languages.items():

print(name.title() + "'s favorite language is " + languages.title() + ".\n")

'''遍历字典中的所有键 .keys()

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

for k in favorite_languages.keys():

print(k.title())

'''下面来打印两条消息,指出两位朋友喜欢的语言。我们像前面一样遍历字典中的名字,但在

名字为指定朋友的名字时,打印一条消息,指出其喜欢的语言:'''

friends=['phil','sarah']

for name in favorite_languages.keys():

print(name.title())

if name in friends:

print('\nHi ' + name.title() + ", I see your favoriate language is " +

favorite_languages[name].title() + "!")

'''你还可以使用keys() 确定某个人是否接受了调查。下面的代码确定Erin是否接受了调查:'''

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

print('\nEric, please take our poll!!\n')

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

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

print(name.title() + ', thank you for taking the poll!\n')

'''遍历字典中的所有值 .values()'''

print('the following languages have been mentioned: ')

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

print(language.title())

'''列表可能包含大量的重复项。为剔除重复项,可使用集合(set)。

集合类似于列表,但每个元素都必须是独一无二的:'''

print('\nHere I use set function to find the unique languages: ')

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

print(language.title())

#try:

#6-4

lan={'sas':'statistic','r':'uni','python':'pachong','vba':'excel','tableau':'visulization'}

lan['keys']='keys()'

lan['values']='values()'

lan['if']='if-elif-else'

lan['title']='title()'

lan['sorted']='sorted()'

for la in lan.keys():

print(la.title() + ': is about \n\t' + lan[la] +'.\n')

#6-5

river={'nile':'egypt','changjiang':'china','roro':'germany'}

for ri in river.keys():

print(ri.title() + ' rans through ' + river[ri].title() + '.\n')

for ri_name in river.keys():

print(ri_name.title())

for country in river.values():

print(country.title())

#6-6

list={'a':'python','b':'sas','c':'c++','d':'vba','e':'tableau'}

new=['d','e','f','x','y','z']

for names in list.keys():

if names in new:

print('\nHi ' + names.title() + ' thank you for your poll! Enjoy ' + list[names] + '.')

else:

print('\nHi ' + names.title() + ' please poll, we are waiting for your option about ' + list[names] + '.')

'''

#6.4 嵌套 p58

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

在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。正如下面的示例

将演示的,嵌套是一项强大的功能。'''

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)

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

aliens=[]

# 创建30个绿色的外星人

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('\nTotal number of aliens: ' + str(len(aliens)) + '.\n')

#我们可以使用for 循环和if 语句来修改某些外星

#人的颜色。例如,要将前三个外星人修改为黄色的、速度为中等且值10个点,可以这样做:

for alien in aliens[0:3]:

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

for alien in aliens[0:5]:

print(alien)

print('....\n')

'''在字典中存储列表

例如,你如何描述顾客点的比萨呢?如果使用列表,只能存储要添加的比萨配料;但如果使用字典,

就不仅可在其中包含配料列表,还可包含其他有关比萨的描述。'''

# 存储所点比萨的信息

pizza = {'crust': 'thick','toppings': ['mushrooms', 'extra cheese'],}

# 概述所点的比萨

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

for toppings in pizza['toppings']:

print('\t' + toppings)

#another case:

favorite_languages={'jen': ['python', 'ruby'],'sarah': ['c'],

'edward': ['ruby', 'go'],'phil': ['python', 'haskell']}

for name, languages in favorite_languages.items():

if len(languages) > 1:

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

for lan in languages:

print('\t' + lan.title())

else:

for onelan in languages:

print('\n' + name.title() + " 's favorite language is: "

+ onelan.title() + '!\n')

'''在字典中存储字典 p60

可在字典中嵌套字典,但这样做时,代码可能很快复杂起来。例如,如果有多个网站用户,每个都

有独特的用户名,可在字典中将用户名作为键,然后将每位用户的信息存储在一个字典中,并将

该字典作为与用户名相关联的值。在下面的程序中,对于每位用户,我们都存储了其三项信息:

名、姓和居住地;'''

users={'aeinstein':{'first':'albert','last':'einstein','location':'princeton'},

'mcurie': {'first': 'marie','last': 'curie','location': 'paris',},}

for username, userinfo in users.items():

print('\nUsername: ' + username.title())

fullname=userinfo['first'] + " " + userinfo['last']

location=userinfo['location']

print('\tFull name: ' + fullname.title())

print('\tLocation: ' + location.title())

#try:

#6-8

pets=[]

pet={'type':'dog','name':'andrew'}

pets.append(pet)

pet={'type':'cat','name':'jason'}

pets.append(pet)

for pet in pets:

print("\nHere's where I know about " + pet['name'].title() + ':')

for key, value in pet.items():

print('\t' + key + ': ' + value + '.')

#6-9

favorite_places={'peter':['beijing'],'jason':['germany','hong kong'],

'mia':['london','frankfurt','berlin'],}

for name, place in favorite_places.items():

print('\nHi ' + name.title() + ', these are the places you want to visit: ')

for dd in place:

print('\t' + dd.title())

#6-10

favorite_numbers = {

'mandy': [42, 17],

'micah': [42, 39, 56],

'gus': [7, 12],

}

for name, numbers in favorite_numbers.items():

print('\n' + name.title() + ' likes the following numbers: ')

for numb in numbers:

print('\t' + str(numb) +'.')

#6-11

cities = {

'santiago': {

'country': 'chile',

'population': 6158080,

'nearby mountains': 'andes',

},

'talkeetna': {

'country': 'alaska',

'population': 876,

'nearby mountains': 'alaska range',

},

'kathmandu': {

'country': 'nepal',

'population': 1003285,

'nearby mountains': 'himilaya',

}

}

for city, info in cities.items():

country=info['country'].title()

population=info['population']

nearby=info['nearby mountains'].title()

print('\nCity ' + city.title() + ' is in ' + country + '.')

print(' It has a population of about ' + str(population) + '.')

print(' The ' + nearby + ' moutains are nearby.')

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180502G1U4TI00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券