Day12:字典(dictionary)

壹、Python 创建字典(dictionary)的方式有两种:

1.使用 {}

[In]
price={'soda':25,"juice":30}

print(price)
[Out]
{'soda': 25, 'juice': 30}

2.使用dict()

[In]
price=dict(Soda=25,Juice=30)
print(price)
[Out]
{'Soda': 25, 'Juice': 30}

贰、如何存取字典内元素

1.使用 [] 符号,传入Key的名称

[In]
price=dict(Soda=25,Juice=30)
print(price["Soda"]) #(name["St"])
[Out]
25

2.透过回圈来读取字典内每个元素

[In]
price=dict(Soda=25,Juice=30)
for pricex in price.items(): #dict.items()返回可遍历的(key,value) 之数
    print(pricex)
[Out]
('Soda', 25)
('Juice', 30)

参、新增字典中元素的方法

1.dict[key] = value

[In]
price=dict(Soda=25,Juice=30)
price['Hot dog']="25"
print(price)
[Out]
{'Soda': 25, 'Juice': 30, 'Hot dog': '25'}

2.update函数
用在一次要增加大量值时
dictname.update(dictn)

[In]
price={"Soda":'25','Juice':'30'}
snack={"choclate":'30',"Hot dog":'35','orange':'free'}
price.update(snack)
print(price)
[Out]
{'Soda': '25', 'Juice': '30', 'choclate': '30', 'Hot dog': '35', 'orange': 'free'}

肆、删除字典中元素办法

1.del并且於 [] 符号中输入要删除的元素名称

[In]
price={"Soda":'25','Juice':'30'}
snack={"choclate":'30',"Hot dog":'35','orange':'free'}
price.update(snack)
del price["Soda"]
print(price)
[Out]
{'Juice': '30', 'choclate': '30', 'Hot dog': '35', 'orange': 'free'}

3..clear
用来清除字典内全部元素

[In]
price={"Soda":'25','Juice':'30'}
snack={"choclate":'30',"Hot dog":'35','orange':'free'}
price.update(snack)
price.clear()
print(price)
[Out]
{}

伍、寻找字典内元素

1.get()

[In]
price={"Soda":'25','Juice':'30'}
snack={"choclate":'30',"Hot dog":'35','orange':'free'}
price.update(snack)
print(price.get("Soda"))
#if cola这个值不再字典内回传"0"
print(price.get("cola",0))
[Out]
25
0

陆、结语

字典内还有很多可以调动的指令但我们今天只介绍这几个,感谢大家的收看!

Source:

https://ppt.cc/fWDNux


<<:  「 A Prediction Approach for Stock Market Volatility Based on Time Series Data 」 ieee access 改写 intro

>>:  [Python学习笔记] 文件I/O-Day2

第12车厢-table界的神器!DataTables介绍篇(2)

延续上篇<第11车厢-table界的神器!DataTables介绍篇(1)>,今日再介...

[D17] ML机器学习(入门)

之前有提到 CNN 业会用在 ML ,那甚麽是 ML 呢? Machine Learning 机器学...

Day 15: 人工智慧在音乐领域的应用 (AI作曲-马可夫模型 Markov Model一)

今天我们先从马可夫模型 (Markov Model) 开始聊聊他是如何用在音乐作曲上的。 在第十三天...

自动化测试,让你上班拥有一杯咖啡的时间 | Day 21 - drag and drop 的用法

此系列文章会同步发文到个人部落格,有兴趣的读者可以前往观看喔。 当网站有 to-do list 时...

Day25 - 【概念篇】Keycloak使用基本概念 - 第一部分: Scopes & Claims

本系列文之後也会置於个人网站 这之前看到的scopes 之前已经看到我一些使用scope的地方: ...