- 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
- 如何将输入的字符串,改变其中的某些元素,然后重新输出