2014-12-19 24 views
0

從O'Reilly的「用於數據分析的Python」中的示例中執行一些數據處理。Python TypeError:無法將字典更新序列元素#1轉換爲序列

我們提供以下格式的數據開始:

In [108]: data.CATEGORY[:5] 
Out[108]: 
0   1. Urgences | Emergency, 3. Public Health, 
4       1. Urgences | Emergency, 
5      5e. Communication lines down, 
6 4. Menaces | Security Threats, 4e. Assainissem... 
7      4. Menaces | Security Threats, 
Name: CATEGORY, dtype: object 

這本書,然後勾畫出一個過程去除週期和「|」從每個條目創建一本詞典,使用以下定義;

def get_all_categories(cat_series): 
    cat_sets = (set(to_cat_list(x)) for x in cat_series) 
    return sorted(set.union(*cat_sets)) 

def get_english(cat): 
    code, names = cat.split('.') 
    if '|' in names: 
     names = names.split(' | ')[1] 
    return code, names.strip() 

第一步進細,創造獨特類別的列表;

In [109]: all_cats = get_all_categories(data.CATEGORY) 

In [110]: all_cats[:5] 
Out[110]: 
['1. Urgences | Emergency', 
'1a. Highly vulnerable', 
'1b. Urgence medicale | Medical Emergency', 
'1c. Personnes prises au piege | People trapped', 
'1d. Incendie | Fire'] 

但是,使用第二個定義的結果如下:

In [116]: english_mapping = dict(get_english(x) for x in all_cats) 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-116-e69c3419c341> in <module>() 
----> 1 english_mapping = dict(get_english(x) for x in all_cats) 

TypeError: cannot convert dictionary update sequence element #1 to a sequence 

爲一個Python菜鳥一點點的幫助,請:)

+0

在您提供的輸入數據上運行時,我不會收到此錯誤。 –

+0

只是在另一臺計算機上再次嘗試它,我仍然得到相同的TypeError。我忘了輸入get_all_categories定義所需的以下定義: 'def to_cat_list(catstr): stripped =(x.strip()for catstr.split(',')) return [x爲x在剝離如果x]' 不知道你是如何得到沒有斯科特的代碼工作... – user3334415

+0

@ user3334415我也沒有得到一個錯誤。鏈接在這裏:http://codepad.org/4uYUiIoS注意:我使用了一個快捷方式,並簡單地使用了您在'all_cats'(前五個元素)中發佈的摘錄進行直接分配,但我對關於全部內容的瞭解不夠你正在加載的數據是否會導致你的結果不同。 – rchang

回答

0

感謝您的幫助球員,看來我只是莫名其妙的白癡。試過所有相同的代碼,無論出於何種原因,今天它的工作原理。如果任何人有任何想法,我可能做錯了拋出這個特定的TypeError,我會很感激。

2

下面是解:

  1. 「可以詞典更新序列元素#1不轉換爲序列」 ---因爲在表達空值「get_english(X),用於all_cats x」的,所以它不能轉換成字典;

  2. 爲什麼?

def get_english(cat): 
    code,names=cat.split('.') 
    if '|' in names: 
     names=names.split('|')[1] 
     return code,names.strip() 

----這是問題所在,最後一行不應該縮進,如果沒有,你會得到一些null值。

相關問題