Pradeep
Pradeep

Reputation: 303

Replace multiple values in dictionary in Python 3

I want to replace multiple values in a list of dict. Example:

# this will set the schema and table dynamically based on the input.
input = {'schema_name': 'test_schema', 'stage_table': 'test_table'}
# need to replace the schemaname and stagetable from the input dict
output = [{id:100, 'query':'SELECT DISTINCT column FROM ${SchemaName}.${StageTable}'}]
# desired output
final_output = select distinct column_name from test_schema.test_table

Upvotes: 2

Views: 641

Answers (1)

MSeifert
MSeifert

Reputation: 152657

There is a format-method for strings but you need to adjust the variable names:

# this will set the schema and table dynamically based on the input.
fill = {'schema_name': 'test_schema', 'stage_table': 'test_table'}
# need to replace the schemaname and stagetable from the input dict
output = [{id:100, 'query':'SELECT DISTINCT column FROM ${schema_name}.${stage_table}'}]

I adjusted the names in and of you input-array so that they matched the signature of your string. And now I'll show you how you can use the format:

output[0]['query'].format(**fill)
#'SELECT DISTINCT column FROM $test_schema.$test_table'

to get your desired result.

Upvotes: 3

Related Questions