'Inserting multiple values into a string
I am trying to run this command but need to insert new two variables for every time I run this command. I think the right approach is to loop through a dictionary and add in the two variables each loop. Ive never looped through a dictionary where there were multiple values per key. Let me know if there are any other approaches to consider.
sample_dict = {key0: ['source0','parameter0'],
key1: ['source1','parameter1'],
key2: ['source2','parameter2'],
key3: ['source3','parameter3']}
for values in sample_dict:
example_cmd = "set -a; source ~/.bash_profile; python3 $path/file.py \
--dbtype db --config-dir $CONFIG_DIR \
--db-conn-config-file db.conf \
--sqlfile $path/{source} \
--params {parameter}"
example_cmd
Solution 1:[1]
I'm not sure exactly what you want to achieve, but iterating through a dictionary in the way you did will actually iterate over the keys, not the values. To iterate over just values, you can use:
for value in sample_dict.values():
...
To iterate over both in pairs, use:
for key, value in sample_dict.items():
...
In your specific case, you could do something like:
for source, parameter in sample_dict.values():
...
This will iterate only over the values (which are lists in your case) and expand each list into the source
and parameter
variables, as each list has exactly two elements. You have to be careful not to have fewer than 2 items in each list in the dict, as it will lead to a runtime error otherwise.
Also, note that both the values()
and items()
methods return an iterator (generator), not a list.
Solution 2:[2]
You're looping through the keys, not the values. You need to loop through sample_dict.values()
.
Then you can use spread assignment to set the source
and parameter
variables to the two elements of each list.
If you're substituting variables with {variable}
you need to use an f-string.
for source, parameter in sample_dict.values():
example_cmd = f"set -a; source ~/.bash_profile; python3 $path/file.py \
--dbtype db --config-dir $CONFIG_DIR \
--db-conn-config-file db.conf \
--sqlfile $path/{source} \
--params {parameter}"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | TheEdgeOfRage |
Solution 2 | Barmar |