開始使用免費開始

Dictionaries

在 R 裡,字典和具名向量、清單很像,都會提供名稱(或稱鍵)讓你存取值。Python 中的字典是用一對大括號 { } 建立,並傳入由鍵和值組成的成對資料。鍵與值之間用冒號分隔。 例如,要建立一個鍵為 'a'、值為 1 的字典,你可以這樣寫:

d = {'a': 1}

多組鍵值對之間用逗號分隔。 若要用鍵來存取值,可以使用方括號(就像從清單擷取子集合一樣),但這裡不是用索引,而是放入鍵:

d = {'a': 1, 'b': 2}
print(d['a'])

1

person_list 已在 IPython 殼層中列印,並可在你的工作環境中使用。

本練習屬於課程

給 R 使用者的 Python

檢視課程

練習說明

  • 以殼層中列印出的 person_list 建立對應的字典版本。請使用鍵 fnamelnamesexemployedtwitter_followers
  • person_dict 中擷取並列印名字與姓氏(鍵為 fnamelname)。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Create a dictionary form of the employee information list
person_dict = {
    'fname': ____,
    'lname': ____,
    'sex': ____,
    'employed': ____,
    'twitter_followers': ____
}

# Get the first and last names from the dict
print(____)
print(____)
編輯並執行程式碼