2016-04-05 14 views
0

APIからの応答があり、時には'Selections'というオプションのキーがあります。それは私が以下のようなMarketPricesで'Selections': []がしたいキーがない場合:特定のリスト内でsetdefaultを使用してデフォルト値を設定する

{'MarketPrices': [{'Selections': [], '_Id': 7308747L, '_ReturnCode': 16}, 
        {'_Id': 1L, '_ReturnCode': 16}], 
'ReturnStatus': {'_CallId': 7bc619bd-2805-4205-85ff-6fa5b48ea899, 
        '_Code': 0, 
        '_Description': Success}, 
'Timestamp': datetime.datetime(2016, 4, 3, 21, 14, 19, 726967, tzinfo=<suds.sax.date.FixedOffsetTimezone object at 0x7f805fffed50>)} 

を私はdict.setdefault('Selections', [])で、デフォルトのキーを設定しようとしていますが、私は得る:

{'MarketPrices': [{'Selections': [], '_Id': 7308747L, '_ReturnCode': 16}, 
        {'_Id': 1L, '_ReturnCode': 16}], 
'ReturnStatus': {'_CallId': 7bc619bd-2805-4205-85ff-6fa5b48ea899, 
        '_Code': 0, 
        '_Description': Success}, 
'Selections': [], 
'Timestamp': datetime.datetime(2016, 4, 3, 21, 14, 19, 726967, tzinfo=<suds.sax.date.FixedOffsetTimezone object at 0x7f805fffed50>)} 

は、どのように私はそれを指定することができますデフォルト値は'MarketPrices'である必要がありますか?

+0

を上書きするよう、変数名dictを使用しないようにしよう、私はMarketPrices'' '「'における第二の辞書からSelections''キー」を削除リストと '' ReturnStatus'' dicitonaryです。これらは明らかにコードの試みによって追加されませんでした。 –

答えて

2

問題は、あなたが親のdictに「選択」のデフォルト値を更新しているということである

ていますが、内側の辞書オブジェクトの値を更新する必要があります。

# assuming that the super_dict object will always have "MarketPrices" 
for sub_dict in super_dict['MarketPrices']: 
    sub_dict.setdefault('Selections':[]) 

ヒント:それは組み込み型コンストラクタdict

関連する問題