所以,我有以下内容:
values = """ { "exchange_code": "GDAX", "exchange_market": "BTC/USD", "type": "asks" } """
正如您所知,""",值必须是字符串文字。但是,我想生成几个值,这些值只有第一个键" exchange_code"的值已更改。我如何能够使用for循环进行迭代,并创建几个相同类型的字符串文字,只更换第一个值?到目前为止,我发现没有任何东西逃脱它,对str的类型转换在生成正确的输出方面不起作用。
答案 0 :(得分:3)
使用json
模块解析字符串,更改您喜欢的结果字典的任何部分,然后再将它们转储为json-strings。
>>> import json
>>> values = """ { "exchange_code": "GDAX", "exchange_market": "BTC/USD", "type": "asks" } """
>>>
>>> d = json.loads(values)
>>> alternatives = ['XADG', 'ABCD']
>>>
>>> result = []
>>> for alt in alternatives:
... d['exchange_code'] = alt
... result.append(json.dumps(d))
...
>>> result
['{"type": "asks", "exchange_code": "XADG", "exchange_market": "BTC/USD"}', '{"type": "asks", "exchange_code": "ABCD", "exchange_market": "BTC/USD"}']
或者作为Python 3中更简洁的理解:
>>> [json.dumps({**d, 'exchange_code': alt}) for alt in alternatives]
['{"type": "asks", "exchange_market": "BTC/USD", "exchange_code": "XADG"}', '{"type": "asks", "exchange_market": "BTC/USD", "exchange_code": "ABCD"}']