'Key values from one dict into another
SOME VERY BASIC question here but for some reason I can’t get a proper solution… I would like to obtain a chosen key values from one dict and move them to another - dict_from_dict and thens tore it in a list - serp_position_output_list
dict1 = {
'request_info': {'success': True, 'credits_used': 2120, 'credits_used_this_request': 1, 'credits_remaining': 2880,
'credits_reset_at': '2022-06-03T09:50:04.000Z'},
'search_parameters': {'q': 'product_name', 'google_domain': 'google.sk', 'location': 'Slovakia', 'gl': 'sk',
'hl': 'sk', 'page': '1', 'num': '100', 'include_answer_box': 'true', 'output': 'json',
'engine': 'google'},
}
What I did:
serp_position_output_list = []
for k,v in dict1.items():
dict_from_dict = {
'credits_used': v['request_info']['credits_used'], #expected credits_used key value here = 2120
'q': v['search_parameters']['q'], #expected value - product_name
'country': v['search_parameters']['location'], #Slovakia
serp_position_output_list.append(dict_from_dict)
print(serp_position_output_list)
# Expected output:
serp_position_output_list = [{'credits_used': 2120,
'q': 'product_name',
'country': 'Slovakia'}]
When I iterate over dict1[‘search_parameters’] to get ‘q’ key value its all right - working but when I try to iterate over dict1 (because I want to obtain both ‘request_info’ key values and ‘search_parameters’ key values it doesn’t work that way. I am wondering why also this does not work that way:
serp_position_output_list = []
for k in dict1:
dict_from_dict = {
'credits_used': k['request_info']['credits_used'], #expected credits_used key value here = 2120
'q': k['search_parameters']['q'], #expected value - product_name
'country': k['search_parameters']['location'], #Slovakia
serp_position_output_list.append(dict_from_dict)
print(serp_position_output_list)
TypeError: string indices must be integers
edit - ok we have a dict1
dict1 = {
'request_info': {'success': True, 'credits_used': 2120, 'credits_used_this_request': 1, 'credits_remaining': 2880,
'credits_reset_at': '2022-06-03T09:50:04.000Z'},
'search_parameters': {'q': 'product_name', 'google_domain': 'google.sk', 'location': 'Slovakia', 'gl': 'sk',
'hl': 'sk', 'page': '1', 'num': '100', 'include_answer_box': 'true', 'output': 'json',
'engine': 'google'},
'request_info': {'success': True, 'credits_used': 2120, 'credits_used_this_request': 1, 'credits_remaining': 2880,
'credits_reset_at': '2022-06-03T09:50:04.000Z'},
'search_parameters': {'q': 'product_name', 'google_domain': 'google.sk', 'location': 'Slovakia', 'gl': 'sk',
'hl': 'sk', 'page': '1', 'num': '100', 'include_answer_box': 'true', 'output': 'json',
'engine': 'google'},
}
and now for loop to get a
request_info['credits_used'],
search_parameters['q'],
search_parameters['location']
values
HOW? Is it more clear now?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
