在特定lis中使用setdefault设置默认值

2024-09-26 22:12:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我从API得到一个响应,有时它有一个名为'Selections'的可选键。如果没有密钥,我希望市场价格如下:

{'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'中?你知道吗


Tags: iddatetimedatecodedescriptiontimestampsudssuccess
1条回答
网友
1楼 · 发布于 2024-09-26 22:12:02

问题是您正在更新父dict中“Selections”的默认值

但是您需要更新内部dictionary对象中的值。你知道吗

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

提示:尽量不要使用变量名dict,因为它将重写内置类型构造函数dict

相关问题 更多 >

    热门问题