Reputation: 15
I am trying to build dictionary from string can someone help me to build the efficient way.
I have api which takes string with comma separate value and returns if value if API has matching values example:
# my paramaters to my API car, bike, moter-cycle, airplane, boat
# www.api.com?words=car,bike,moter-cycle,airplane,boat
field_json = json.loads(response.text)
data = field_json['response']
list1=""
for i in data['docs']:
list[i['keyword_s']]= i['url_s']
list1 = str(list)
print(list)
return list1
from above I just get
{'bike':'http://bikes.com/bikes',
'boat':'http://boat.com/boat'}
if API find bike and boat as matching I would need my dictonary as
{'car':'none',
'bike':'http://bikes.com/bikes',
'moter-cycle': 'none',
'airplane':'none',
'boat':'http://boat.com/boat'
}
Upvotes: 0
Views: 69
Reputation: 43300
You don't need to involve strings, just fill in hole values in your returned api response
dict_a = {'bike':'http://bikes.com/bikes', 'boat':'http://boat.com/boat'}
keywords = ['car','bike','motorcycle', 'airplane', 'boat']
dict_b = {k: None for k in keywords}
dict_b.update(dict_a)
print(dict_b)
Output
{'car': None, 'bike': 'http://bikes.com/bikes', 'motorcycle': None, 'airplane': None, 'boat': 'http://boat.com/boat'}
Upvotes: 1