小白学Python笔记 Day10

2023.5.13 ~14   第六章 字典 Dictionary ------- { } 用大花括号  ---- 键-值 对。key-value pair

  • 格式:键与值之间:冒号 | 键值对之间,逗号

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

print(字典名['键1'])

print(字典名['键2'])

  • 访问字典中的值:

实例:

refund = student['tuition']
print('Please refund ' + str(refund) + ' to the student.')

  • 添加键值对 - 不关心多个键值对的添加顺序(可能乱序)

字典名[‘新键’] = ‘新值’

有时,先创建空字典,再依次添加键值对。

  • 修改值

字典名[‘原键’] = ‘新值’

实例:跟踪一个机器人移动到的新位置

# 跟踪位置
alien = {'x_position': 0, 'y_position': 25, 'speed': 'slow'}

if alien['speed'] == 'slow':
        x_increment = 1
elif alien['speed'] == 'medium':
        x_increment = 2
else:
        x_increment = 3

alien['x_position'] = alien['x_position'] + x_increment
print('Now the new position is ' + str(alien['x_position']))

>>>  Now the new position is 1

  • 删除键值对 ----- del 字典['键']  ---- -- 永久删除

生活中的字典:词汇表

遍历字典

  • 遍历所有键值对 - for循环

for key, value in 字典名.items( )

遍历所有键 - keys() ------------ 别忘记+ s --------- keys()其实可省略

friend = {'first_name': 'Peter', 'last_name': 'On', 'age': 33, 'city': 'Auckland'}
for key in friend.keys():
        print(key.title())

----- 用当前键访问与之关联的值

fav_languages = {'Jack': 'English',
                                'Philip': 'Japanese',
                                'Amy': 'Italian',
                                'Eric': 'Germany'
                                }

friends = ['Amy', 'Peter']
for name in fav_languages.keys():
                                print(name)

                                if name in friends:    ------------ 注意缩进!!隶属于for循环
                                        print('Hi! I know your favorite language is ' + fav_languages[name] + '!')

按顺序遍历所有键

用for循环对返回值进行排序,如sorted() --------- 按字母顺序

friend = {'first_name': 'Peter', 'last_name': 'On', 'age': 33, 'city': 'Auckland'}

for key in sorted(friends.keys()):

        print(key)

>>> Age
       City
       First_Name
       Last_Name

遍历所有值 - values() 加上 for循环

friend = {'first_name': 'Peter', 'last_name': 'On', 'age': 33, 'city': 'Auckland'}
for value in friend.values():
        print(value)

集合set() 剔除重复项

fav_food = {'Peter': "coco",
        'Amy': 'sushi',
        'Cathy': 'salad',
        'John': 'sushi',
        }
for value in set(fav_food.values()):
        print(value)

>>> sushi
        coco
        salad

------------- 做几个练习 -------------

嵌套 - 列表存字典/字典存列表/字典套字典 - !!!重点难点,反复练习!

  • 字典列表

student_01 = {'Age': 23, 'Name': 'Peter', 'Sex': 'M'}    ------------- 三个字典
student_02 = {'Age': 22, 'Name': 'Cathy', 'Sex': 'F'}
student_03 = {'Age': 21, 'Name': 'Amy', 'Sex': 'F'}

students = [student_01, student_02, student_03]        --------- 把三个字典放进一个列表中
for student in students:
        print(student)

可用range()自动生成多个人

students = []
for student_number in range(30):
        new_student = {'Age': 23, 'Name': 'Peter', 'Sex': 'M'}
        students.append(new_student)

for student in students[:5]:
print(student)
print('...')

print('Total number of students: ' + str(len(students)))


for student in students[:3]:
        if student['Age'] == 23:
                student['Age'] = 20
                student['Name'] = 'Cathy'
                student['Sex'] = 'F'

  • 在字典中存储列表 --------------  嵌套层级不应太多 - 有更简单的

pizza = {'color': 'blue', 'ingredients': ['onion', 'potato']}
print('You get a ' + pizza['color'] + ' pizza made by the following ingredients:')
        for ingredient in pizza['ingredients']:
                print(ingredient)

fav_food = {'Peter': ["coco"],     --------------------- 即使只有一个值,也要用[].所有都要用列表
        'Amy': ['sushi', 'salad'],
        'Cathy': ['salad'],
        'John': ['sushi'],
        }

for name, foods in fav_food.items():
        if len(foods) > 1:
                print(name + "'s favorite foods are" + ': ')
                for food in foods:
                        print(food)
        elif len(foods) <= 1:
                print(name + "'s favorite food is" + ': ')
                for food in foods:
                        print(food)

  • 在字典中存储字典

user = {
        'Amy': {'First_name': 'Amy',
                'Last_name': 'Colando',
                },
        'Jack':{'First_name': 'Jack',
                'Last_name': 'Dawn',
                },
        }

---------------- 做几个练习--------------第六章 字典 完--------------明天用户输入与while循环-----

在路上不方便就看书  然后后面练习

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值