I have this string https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500
. I want to concatenate this string with the other string &filters[city]=Mumbai&filters[polutant_id]=PM10
. The second string should be added dynamically based on the dictionary below.
criteria = {'city':["Mumbai","Delhi"], 'polutant_id': ["PM10", "NO2"]}
The output below contains 4 strings as the above dictionary has 4 possible combination of city and polutant_id.
Output
"https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filters[city]=Mumbai&filters[polutant_id]=PM10" "https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filters[city]=Delhi&filters[polutant_id]=PM10" "https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filters[city]=Mumbai&filters[polutant_id]=NO2" "https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filters[city]=Delhi&filters[polutant_id]=NO2"
What I tried
In order to get all the possible combinations I am using the function below –
import pandas as pd import itertools def expand_grid(data_dict): rows = itertools.product(*data_dict.values()) return pd.DataFrame.from_records(rows, columns=data_dict.keys()) criteriaAll = expand_grid(criteria)
To fetch filters, using the code below –
['&filters[' + ls+ ']=' for ls in list(criteria.keys())]
I am stuck in achieving the desired output. Note – Dictionary can have more or less than 2 keys.
Advertisement
Answer
I don’t think you need the complexity of a dataframe to solve this. First create a list of tuples of key/value pairs from criteria, then take the cartesian product of that list and iterate the tuples in the product to produce the filter strings:
base = 'https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500' criteria = {'city':["Mumbai","Delhi"], 'polutant_id': ["PM10", "NO2"]} criteriaAll = [[(k, v) for v in criteria[k]] for k in criteria] result = [base + ''.join(f'&filter[{ls}]={value}' for ls, value in p) for p in itertools.product(*criteriaAll)]
Output:
[ 'https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filter[city]=Mumbai&filter[polutant_id]=PM10', 'https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filter[city]=Mumbai&filter[polutant_id]=NO2', 'https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filter[city]=Delhi&filter[polutant_id]=PM10', 'https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filter[city]=Delhi&filter[polutant_id]=NO2' ]