Python 3 《dictionary》入门练习

#!/usr/bin/env python
# -*- coding:utf-8 -*- 
# author: Christal date: 2021/11/19

# --------简单的字典创建和打印--------
alien_0 = {'color': 'green', 'points': 6}

print(alien_0['color'])
print(alien_0['points'])

print("The color of the alien is " + alien_0['color'] + '.')  # 打印出字典中关于alien 的颜色
alien_0['color'] = 'yellow'
print('The color of the alien is now ' + alien_0['color'] + '.')  # 修改后打印出字典中关于alien 的颜色

new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")

# --------增加字典的内容-------------
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

alien_1 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original x-position: " + str(alien_1['x_position']))

# -------据外星人当前速度决定将其移动多远---------
if alien_1['speed'] == 'slow':
    x_increment = 1
elif alien_1['speed'] == 'medium':
    x_increment = 2
else:
    x_increment = 3

alien_1['x_position'] = alien_1['x_position'] + x_increment
print('The new position of alien is ' + str(alien_1['x_position']))

# ------删除字典中元素---------
del alien_1['speed']
print('The information of alien now is ' + str(alien_1))

# -------类似对象组成的字典------------
favorites = {'Jam': 'python',
             'Tony': 'C++',
             'Christal': 'C#',
             'sarah': 'ruby',
             'Han': 'python'}
print("Christal's favourite language is " + str(favorites['Christal'].title()) + '.')

# ------遍历字典的所有键—值对、键或值---------
for name, language in favorites.items():
    print('\n Key:' + name)  # 遍历字典的所有的键
    print('Value:' + language)  # 遍历字典的所有的值
    print("\r" + name.title() + "'s favourite language is " + language.title())  # 遍历字典的所有键—值对

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

friends = ['Christal', 'Edward']
for name in favorites:  # 遍历字典时,会默认遍历所有的键, 与上述输出一致
    print(name.title())
    if name in friends:
        print("My friend " + name.title() + ', ' + 'I see your favoriate language is '
              + favorites[name].title() + '!')
if 'erin' not in favorites.keys():  # 检查erin是否在字典中保存
    print('erin, please take our poll! ')
for name in sorted(favorites):  # 也可以 for name in sorted(favorites.keys()):
    print(name.title() + ", thank you for taking the poll.")

print("The following languages have been mentioned:")
for language in favorites.values():  # 遍历字典的所有的值
    print(language.title())

print("The following languages have been mentioned:")
for language in set(favorites.values()):  # 遍历字典的所有的值
    # 有没有set()函数都可以提取字典中所有的value, 加入set()之后,保证不会重复
    print(language.title())

# -------------嵌套------------
# 有时,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。
# 可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典

# --------列表中存储字典---------
alien_0 = {'color': 'green', 'points': 5, 'speed': 'slow'}
alien_1 = {'color': 'yellow', 'points': 10, 'speed': 'fast'}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
    print(alien)

aliens = []
for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)

for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10

for alien in aliens[:5]:
    print(alien)
print("... ")

print("The number of the aliens is " + str(len(aliens)))

# ---------字典中存储列表(1)-------------
pizzas = {'crust': 'thick',
          'toppings': ['mushroom', 'peppers', 'extra cheese']}  # pizza 的配料列表
print("You ordered a " + pizzas['crust'] + "-crust pizza " + "with the following toppings:")
for topping in pizzas['toppings']:
    print("\t" + topping)

#----------字典中存储列表(2)-------------
favorite_languages = {'jen': ['python', 'ruby'],
                      'sarah': ['c'],
                      'edward': ['ruby', 'go'],
                      'phil': ['python', 'haskell'],
                      }
for name, languages in favorite_languages.items():
    print("\n" + name.title()+ " 's favorite language are: ")
    for language in languages:
        print("\t" + language.title())


#------------字典中嵌套字典------------------
users={'aeinstein':{'first':'alberit',
                    'last':'einstein',
                    'location':'princeton',
                    },
    'mcurie':{'first':'marie',
              'last':'curie',
              'location':'paris',
              },
    }
for user_name, user_info in users.items():
    print("\n Username: "+ user_name)
    full_name= user_info['first']+" "+user_info['last']
    location = user_info['location']
    print('\t'+'Full Name: '+full_name.title())
    print('\t' + 'Location: ' + location.title())

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清韵逐梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值