以更 Pythonic 的方式使用字典

Python 的資料型別

Jason Myers

Instructor

更 Pythonic 的字典操作

  • .items() 方法會回傳可迭代的物件
for gallery, phone_num in art_galleries.items():
    print(gallery)
    print(phone_num)
'Miakey Art Gallery'
'(718) 686-0788'
'Morning Star Gallery Ltd'
'(212) 334-9330'}
'New York Art Expo Inc'
'(212) 363-8280'
Python 的資料型別

檢查字典是否有資料

  • .get() 為檢查鍵做了很多事
  • in 運算子更有效率且更清楚
'11234' in art_galleries
False
if '10010' in art_galleries:
    print('I found: %s' % art_galleries['10010'])
else:
    print('No galleries found.')
I found: {'Nyabinghi Africian Gift Shop': '(212) 566-3336'}
Python 的資料型別

一起來練習吧!

Python 的資料型別

Preparing Video For Download...