2016-07-11 73 views
0

字典比方說,我有這樣的功能:如何嘲笑在Python

def do_something(dict_obj): 
    # access to the dict_obj then do some stuff 
    eg. 
    if dict_obj['doors']: 
     do_something_with_doors() 
    map_car_make(dict_obj['make']) 
    ... 

    if dict_obj['is_active']: 
     do_something_else() 

我想嘲笑dict_objis_active元素並不在意休息,我該怎麼做呢?

+2

爲什麼要嘲笑一個簡單的數據結構?爲什麼不''dict_obj ['is_active'] = True'?通常這是_behavior_應該被剔除掉,而不是數據。 –

+0

此外,如果你不關心裏面的值,你總是可以使用'collections.defaultdict' –

+0

@MattBall,因爲函數中還有其他邏輯可以使用dict_obj中的其他元素,查看更新後的代碼 –

回答

0

您可以使用dict.get方法返回您可以模擬is_active條目存在的默認值。