Python编程:从入门到实践(第二版)随书敲代码 第六章 字典

本文介绍了Python编程中字典的基本操作,包括创建、访问、更新和删除键值对。通过示例展示了如何利用字典存储外星人属性、调查结果、词汇表、河流信息和个人资料等,涵盖了字典的遍历、更新、查找和删除功能。此外,还涉及了字典在存储多值、嵌套和循环遍历等方面的应用。
部署运行你感兴趣的模型镜像

alien.py

# 第六章 字典
# 6.1 一个简单的字典
alien_0 = {'color': 'green', 'points': '5'}
print(alien_0['color'])
print(alien_0['points'])

new_points = alien_0['points']
print(f"\nYou just earned {new_points} points!")


print("\n")
print(alien_0)

alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)


print("\n")
alien_0 = {}

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

print(alien_0)


print("\n")
alien_0 = {'color': 'green'}
print(f"The alien is {alien_0['color']}.")

alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}.")


print("\n")
alien_0 = {'x_position': 0,'y_position': 25,'speed':'medium'}
print(f"Original x_position: {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(f"New x_position: {alien_0['x_position']}")


print("\n")
alien_0 = {'color': 'green','points': '5'}
print(alien_0)

del alien_0['points']
print(alien_0)

favorite_languages.py

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

language = favorite_languages['sarah'].title()
print(f"Sarah's favorite language is {language}.")

print("\n")
# 遍历所有键值对items()
for name, language in favorite_languages.items():
    print(f"{name.title()}'s favorite language is {language.title()}.")

print("\n")
# 遍历字典中的所有键keys()
for name in favorite_languages.keys():
    print(name.title())


friends = ['phil','sarah']
for name in favorite_languages.keys():
    print(f"Hi {name.title()}.")

    if name in friends:
        language = favorite_languages[name].title()
        print(f"\t{name.title()}, I see you love {language.title()}!")


print("\n")
# 使用keys()检查是否存在
if 'erin' not in favorite_languages.keys():
    print("Erin,please take our poll!")


print("\n")
# 按特定顺序遍历字典中的所有键
for name in sorted(favorite_languages.keys()):
    print(f"{name.title()}, Thank you taking the poll.")


print("\n")
# 遍历字典中的所有值
print("The following languages have been mentioned:")

for language in favorite_languages.values():
    print(language.title())


print("\n")
# 剔除重复项,使用set集合
print("The following languages have been mentioned:")

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

alien_no_points.py

alien_0 = {'color':'green','speed':'slow'}

#键值错误
#print(alien_0['points'])

#使用get()指定键值
point_value = alien_0.get('points','No point value assigned.')
print(point_value)

person.py

# 练习 6-1 人
# 使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。
# 该字典应包含键 first_name 、last_name 、age 和 city 。将存储在该字典中的每项信息都打印出来。

person = {
    'first_name': 'yutada',
    'last_name': 'hikaru',
    'age': '28',
    'city': 'tokyo',
    }
print(person['first_name'])
print(person['last_name'])
print(person['age'])
print(person['city'])

favorite_numbers1.py

#练习 6-2 喜欢的数
#使用一个字典来存储一些人喜欢的数。请想出 5 个人的名字,并将这些名字用作字典中的键;
#想出每个人喜欢的一个数,并将这些数作为值存储在字典中。打印每个人的名字和喜欢的数。
#为让这个程序更有趣,通过询问朋友确保数据是真实的。

favorite_numbers = {
    'a': 1,
    'b': 2,
    'c': 3,
    'd': 4,
    'e': 5,
    }

number = favorite_numbers['a']
print(f"a's favorite number is {number}.")

number = favorite_numbers['b']
print(f"b's favorite number is {number}.")

number = favorite_numbers['c']
print(f"c's favorite number is {number}.")

number = favorite_numbers['d']
print(f"d's favorite number is {number}.")

number = favorite_numbers['e']
print(f"e's favorite number is {number}.")

glossary.py

# 练习 6-3 词汇表
# Python字典可用于模拟现实生活中的字典,但为避免混淆,我们将后者称为词汇表。
# 想出你在前面学过的5个编程词汇,将它们用作词汇表中的键,并将它们的含义作为值存储在词汇表中。
# 以整洁的方式打印每个词汇及其含义。为此,可以先打印词汇,在它后面加上一个冒号,再打印词汇的含义;
# 也可在一行打印词汇,再使用换行符( \n )插入一个空行,然后在下一行以缩进的方式打印词汇的含义。

glossary = {
    'string': 'A series of characters.',
     'comment': 'A note in a program that the Python interpreter ignores.',
     'list': 'A collection of items in a particular order.',
     'loop': 'Work through a collection of items, one at a time.',
     'dictionary': "A collection of key-value pairs.",
     }

#第一种方法
word = 'string'
print(f"\n{word.title()}: {glossary[word]}")

word = 'comment'
print(f"\n{word.title()}: {glossary[word]}")

word = 'list'
print(f"\n{word.title()}: {glossary[word]}")

word = 'loop'
print(f"\n{word.title()}: {glossary[word]}")

word = 'dictionary'
print(f"\n{word.title()}: {glossary[word]}")

#第二种使用for遍历简写
for k,v in glossary.items():
    print(f"\n{k.title()}: {v}")

glossary1.py

# 练习 6-4 词汇表 2
# 现在你知道了如何遍历字典,请整理你为完成练习 6-3 而编写的代码,将其中的一系
# 列函数调用 print()替换为一个遍历字典中键和值的循环。
# 确定该循环正确无误后,再在词汇表中添加 5 个 Python 术语。
# 当你再次运行这个程序时,这些新术语及其含义将自动包含在输出中。

glossary = {
     'string': 'A series of characters.',
     'comment': 'A note in a program that the Python interpreter ignores.',
     'list': 'A collection of items in a particular order.',
     'loop': 'Work through a collection of items, one at a time.',
     'dictionary': "A collection of key-value pairs.",
     'key': 'The first item in a key-value pair in a dictionary.',
     'value': 'An item associated with a key in a dictionary.',
     'conditional test': 'A comparison between two values.',
     'float': 'A numerical value with a decimal component.',
     'boolean expression': 'An expression that evaluates to True or False.',
     }
for word,definition in glossary.items():
     print(f"{word.title()}: {definition}")

rivers.py

# 练习 6-5 河流
# 创建一个字典,在其中存储三条大河流及其流经的国家。
# 其中一个键值对可能是'nile': 'egypt' 。
# 使用循环为每条河流打印一条消息,如 The Nile runs through Egypt。
# 使用循环将该字典中每条河流的名字都打印出来。
# 使用循环将该字典包含的每个国家的名字都打印出来。

rivers = {
    'nile': 'egypt',
     'mississippi': 'united states',
     'fraser': 'canada',
     'kuskokwim': 'alaska',
     'yangtze': 'china',
     }

for river,country in rivers.items():
    print(f"The {river.title()} runs through {country.title()}.")

print("\nThe following rivers are included in this data set:")
for river in rivers.keys():
 print(f"- {river.title()}")

 print("\nThe following countries are included in this data set:")
for country in rivers.values():
    print(f"- {country.title()}")

favorite_languages1.py

# 练习 6-6 调查
# 在 6.3.1 节编写的程序 favorite_languages.py 中执行以下操作。
# 创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中。
# 遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。
# 对于还未参与调查的人,打印一条消息邀请他参与调查。

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

for name,language in favorite_languages.items():
    print(f"{name.title()}'s favorite language is {language.title()}.")

print("\n")

coders = ['phil','josh','david','becca','sarah','matt','danielle']
for coder in coders:
    if coder in favorite_languages.keys():
        print(f"Thank you for taking the poll, {coder.title()}!")
    else:
        print(f"{coder.title()},what's your favorite programming language?")

aliens.py

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)

print("\n")
# 创建一个用于存储外星人的空列表
aliens = []

# 创建30个绿色的外星人
for alien_number in range(30):
    new_alien = {'color': 'green','points': 5, 'speed': 'slow'}
    aliens.append(new_alien)

# 修改前三个外星人
for alien in aliens[: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

# 显示前5个外星人
for alien in aliens[:5]:
    print(alien)
print("...")

# 显示创建了多少个外星人
print(f"Total number of aliens: {len(aliens)}")

pizza.py

# 存储所点比萨的信息
pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese'],
    }

# 概述所点的比萨。
print(f"You ordered a {pizza['crust']}-crust pizza"
    "with the following toppings:")

for topping in pizza['toppings']:
    print("\t" + topping)

favorite_languages2.py

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

for name, languages in favorite_languages.items():
    print(f"\n{name.title()}'s favorite languages are:")
    for language in languages:
        print(f"\t{language.title()}")

many_users.py

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

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

for username, user_info in users.items():
        print(f"\nUsername:{username}")
        full_name = f"{user_info['first']} {user_info['last']}"
        location = user_info['location']

        print(f"\tFull name: {full_name.title()}")
        print(f"\tLocation: {location.title()}")

people.py

# 练习 6-7 人们
# 在为完成练习 6-1 而编写的程序中,再创建两个表示人的字典,
# 然后将这三个字典都存储在一个名为 people 的列表中。
# 遍历这个列表,将其中每个人的所有信息都打印出来。

# 创建一个用于存储人的空列表。
people = []
# 定义一些人并将他们添加到前述列表中。
person = {
    'first_name': 'eric',
    'last_name': 'matthes',
    'age': 46,
    'city': 'sitka',
    }
people.append(person)

person = {
    'first_name': 'lemmy',
    'last_name': 'matthes',
    'age': 2,
    'city': 'sitka',
    }
people.append(person)

person = {
     'first_name': 'willie',
     'last_name': 'matthes',
     'age': 11,
     'city': 'sitka',
     }
people.append(person)

# 显示列表包含的每个字典中的信息。
for person in people:
    name = f"{person['first_name'].title()} {person['last_name'].title()}"
    age = person['age']
    city = person['city'].title()

    print(f"{name}, of {city}, is {age} year old.")

pets.py

# 练习 6-8 宠物
# 创建多个字典,对于每个字典,都将宠物的名称包含在字典;
# 在每个字典中,包含宠物的类型及其主人的名字。
# 将这些字典存储在一个名为 pets 的列表中,再遍历该列表,
# 并将有关每个宠物的所有信息都打印出来。

# 创建一个用于存储宠物的空列表。
pets = []

# 定义各个宠物并将其存储到列表中。
pet = {
     'animal type': 'python',
     'name': 'john',
     'owner': 'guido',
     'weight': 43,
     'eats': 'bugs',
    }
pets.append(pet)

pet = {
    'animal type': 'chicken',
     'name': 'clarence',
     'owner': 'tiffany',
     'weight': 2,
     'eats': 'seeds',
    }
pets.append(pet)
pet = {
     'animal type': 'dog',
     'name': 'peso',
     'owner': 'eric',
     'weight': 37,
     'eats': 'shoes',
    }
pets.append(pet)

# 打印每个宠物信息
for pet in pets:
    print(f"\nHere's what I know about {pet['name'].title()}:")
    for k, v in pet.items():
        print(f"\t{k}: {v}")

favorite_places.py

# 练习 6-9 喜欢的地方
# 创建一个名为 favorite_places 的字典。在这个字典中,将三个人的名字用作键;
# 对于其中的每个人,都存储他喜欢的 1~3 个地方。
# 为让这个练习更有趣些,让一些朋友指出他们喜欢的几个地方。
# 遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。

favorite_places = {
     'eric': ['bear mountain', 'death valley', 'tierra del fuego'],
     'erin': ['hawaii', 'iceland'],
    'willie': ['mt. verstovia', 'the playground', 'new hampshire'],
    }

for name,places in favorite_places.items():
    print(f"\n{name.title()} like the following places:")
    for place in places:
        print(f"- {place.title()}")

favorite_numbers2.py

# 练习 6-10 喜欢的数 2
# 修改为完成练习 6-2 而编写的程序,让每个人都可以有多个喜欢的数,
# 然后将每个人的名字及其喜欢的数打印出来。

favorite_numbers = {
     'mandy': [42, 17],
     'micah': [42, 39, 56],
    'gus': [7, 12],
     }

for name, numbers in favorite_numbers.items():
     print(f"\n{name.title()} like the following numbers:")
     for number in numbers:
         print(f" {number}")

cities.py

# 练习 6-11 城市
# 创建一个名为 cities 的字典,在其中将三个城市名用作键;
# 对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。
# 在表示每座城市的字典中,应包含 country 、population 和 fact 等键。
# 将每座城市的名字以及有关它们的信息都打印出来。

cities = {
     'santiago': {
         'country': 'chile',
         'population': 6_310_000,
         'nearby mountains': 'andes',
         },
     'talkeetna': {
         'country': 'united states',
         'population': 876,
         'nearby mountains': 'alaska range',
         },
     'kathmandu': {
         'country': 'nepal',
         'population': 975_453,
         'nearby mountains': 'himilaya',
         }
     }

for city, city_info in cities.items():
    country = city_info['country'].title()
    population = city_info['population']
    mountains = city_info['nearby mountains'].title()

    print(f"\n{city.title()} is in {country}.")
    print(f" It has a population of about {population}.")
    print(f" The {mountains} mountains are nearby.")

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值