开始跟着视频学python,第九天mark【字典】

视频位置:138:40
字典
用大括号定义字典。{}

customer = {
    "name":"John Smith",
    "age":30,
    "is_verified":True
}
print(customer["name"])

输出为:

John Smith

如果是没有的值会提示出错。区分大小写。

customer = {
    "name":"John Smith",
    "age":30,
    "is_verified":True
}
print(customer["Name"])   #此处N大写了

会提示:

    print(customer["Name"])
KeyError: 'Name'

可以用get功能,防止程序报错。

customer = {
    "name":"John Smith",
    "age":30,
    "is_verified":True
}
print(customer.get("Name"))   #此处N大写了
print(customer.get("age"))

输出为:

None
30

get也可以赋值

customer = {
    "name":"John Smith",
    "age":30,
    "is_verified":True
}
print(customer.get("birthdate","Jan 1 1980"))   #没有的会赋值
print(customer.get("age","Jan 1 1980"))    #有的不会变
print(customer)      #上面的birthdate并没有添加进来

输出为:

Jan 1 1980
30
{'name': 'John Smith', 'age': 30, 'is_verified': True}

想要改变内容,可以用等号

customer = {
    "name":"John Smith",
    "age":30,
    "is_verified":True
}
customer["name"] = 'Jack Smith'
customer["birthdate"] = "Jan 1 1980"
print(customer["name"])
print(customer)

输出为:

Jack Smith
{'name': 'Jack Smith', 'age': 30, 'is_verified': True, 'birthdate': 'Jan 1 1980'}

小练习:
输入一串数字如:134
输出one two four
我的程序:

phone = {
    "0":"zero",   #注意是冒号
    "1":"one",
    "2":"two",
    "3": "three",
    "4": "four",
    "5": "five",
    "6": "six",
    "7": "seven",
    "8": "eight",
    "9": "nine",
}
user_input = input("phone: ")
for item in user_input:
    print(phone[item])

输出为:

phone: 148
one
four
eight

如果要用get,注意:

print(phone.get(item,"!"))  
#print(phone.get([item],"!")   这个不对,没有中括号

视频主的程序:

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

输出为:

phone: 257t
two  five  seven  !  

和我的区别,视频主把这个输出用字符串串了起来,且加了空格,输出为一行。

split功能

message = input(">")
word = message.split('  ') #将字符串分割成多个单词,分隔关键词为‘’里面的内容
print(word)
word1 = message.split('ab') #将字符串分割成多个单词,分隔关键词为‘’里面的内容
print(word1)
word2 = message.split('m') #将字符串分割成多个单词,分隔关键词为‘’里面的内容
print(word2)

输出为:

>si  abde  cdmaio  king
['si', 'abde', 'cdmaio', 'king']
['si  ', 'de  cdmaio  king']
['si  abde  cd', 'aio  king']

替换某些字符串中字符

message = input(">")
words = message.split(' ') #将字符串分割成多个单词,分隔关键词为‘’里面的内
emojis = {
    ":)":"lalalala",
    ":(":"55555555"
}
output = ""
for word in words:
    output += emojis.get(word,word) +" "
print(output)

输出为:

>MY name is :(  i am happy
MY name is 55555555  i am happy 

视频位置:150:50

猜你喜欢

转载自blog.csdn.net/weixin_42944682/article/details/105703660
今日推荐