dictionary

  • store information come as key-value pairs
  • each key should be unique
  • 通过key获得value
customer = {
    'name':'John Smith',
    'age':'30',
    'is_verified':True
}
customer['name']
customer.get('name')
customer.get('birthday', 'Jan 1')

直接查找,如果不存在该key,会出错。然而调用get方法,可以return None。
get方法中,在key后,可以设置默认值,可以return该默认值

  • update value, create new key-value pair
customer['name'] = Moira
customer['birthday'] = 'Jan 1'

字典练习

phone_num = input('phone: ')
num_trans = {'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'}
output = ''
for num in phone_num:
    output += f'{num_trans.get(num, '!'} '
print(output)

得到的结果

phone: 12345
one two three four five 
  • get函数设置default值
  • get函数防止程序出错

emoiji converter

message = input("> ")
words = message.split(" ")
emojis = {
    ":)": "🙂",
    ":(": "😟"
}
output = ''
for word in words:
    output += emojis.get(word, word) + ' '
print(output)
  • str的split函数能够将字符串按照给定的分隔符号分割开,形成包含独立str的list
  • 如何将输入的字符串,改变其中的某些元素,然后重新输出
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值