開始使用免費開始

重構字典結構

現在你想清理政治人物資料,並把它移到 Dask DataFrame。 不過這些政治人物資料是巢狀結構,因此在能放進 DataFrame 之前,還需要再處理一下。

你想擷取的一個欄位被埋在字典的好幾層裡。這是每位政治人物對應的網站連結。下面的範例顯示它在字典中的存放方式。

record = {
...
 'links': [{'note': '...',
            'url': '...'},],  # Stored here
...
}

裝有政治人物資料的 bag 在你的環境中名為 dict_bag

本練習屬於課程

在 Python 中使用 Dask 進行平行程式設計

檢視課程

練習說明

  • 完成 extract_url() 函式,從字典中擷取 'links' 鍵底下清單中第 0 個元素的 'url',並將其指定到鍵 url
  • extract_url() 函式套用到 bag 的所有元素。

動手互動練習

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

def extract_url(x):
    # Extract the url and assign it to the key 'url'
    x['url'] = x[____][____][____]
    return x
  
# Run the function on all elements in the bag.
dict_bag = ____

print(dict_bag.take(1))
編輯並執行程式碼