iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 9
1
自我挑戰組

Python X 30系列 第 9

python 起手式:dictionary

寫到這裡,真的覺得可以寫滿30天持續不間斷的真的超級強大的,我覺得自己快撐不住了。不過為了能夠學會python,我仍然願意忍受工作的辛苦想耍廢之後,還是要繼續寫下去...... 同時,原本是想自己慢慢寫慢慢自己看的,沒想到居然有這麼多人訂閱這篇文。真是讓我受寵若驚,這也是我必須要繼續寫下去的理由。

python 中也有一個資料型態,叫做“Dictionary”,有點像是php的 associative arrays
php 是這樣表示的:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

而在python當中,dictionary是這樣表示的

>>> age = {'Peter': 35, 'Ben': 37, 'Joe': 43}
>>> age['Peter']
35

而dictionary 和 list一樣可以修改

>>> age['Ben']=38
>>> age
{'Peter': 35, 'Ben': 38, 'Joe': 43}

至於dictionary的刪除或清空則需要這樣

>>> age = {'Peter': 35, 'Ben': 37, 'Joe': 43}
>>> del age['Joe']
>>> age
{'Peter': 35, 'Ben': 37}
>>> age.clear()
>>> age
{}

比較特別的是,dictionary可以轉換成string

>>> age = {'Peter': 35, 'Ben': 37, 'Joe': 43}
>>> len(age)
3
>>> str(age)
"{'Peter': 35, 'Ben': 37, 'Joe': 43}"
>>> type(str(age))
<class 'str'>
>>> type(age)
<class 'dict'>

其他操作

>>> age = {'Peter': 35, 'Ben': 37, 'Joe': 43}
>>> age.get('Ben')
37
>>> age.items()
dict_items([('Peter', 35), ('Ben', 37), ('Joe', 43)])
>>> type(age.items())
<class 'dict_items'>
>>> age.keys()
dict_keys(['Peter', 'Ben', 'Joe'])
>>> age.values()
dict_values([35, 37, 43])

同場加映

>>> age = {'Peter': 35, 'Ben': 37, 'Joe': 43}
>>> list(age.keys())  #可以只取dictionary 的key的list
['Peter', 'Ben', 'Joe']
>>> list(age.values()) #可以只取dictionary 的value的list
[35, 37, 43]

參考資料:
https://www.tutorialspoint.com/python/python_dictionary.htm


上一篇
python 起手式:淺談tuples
下一篇
python 起手式:Functions
系列文
Python X 3030
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
草原狼walfes
iT邦新手 5 級 ‧ 2019-07-19 15:05:58

前輩請教一下
執行
list(age.keys()) #可以只取dictionary 的key的list
出現
TypeError: 'list' object is not callable
是 list不能使用嗎

r567tw iT邦研究生 5 級 ‧ 2019-07-20 05:39:42 檢舉

應該不會不能使用才對,list 是python 內置函數。
你可以把原始碼放上來嗎? 有沒有宣告過age 這個變數呢? 我剛剛查過類似這種錯誤似乎是之前list 有被宣告過,可以先使用

del list

然後再試試看, 底下這兩個參考資料您參考一下:
https://blog.csdn.net/lvsehaiyang1993/article/details/80667921

https://stackoverflow.com/questions/31087111/typeerror-list-object-is-not-callable-in-python/31087151

我要留言

立即登入留言