I am new to Python. Please help me.
Example :
I have 2 different lists indexnameList
and payloadList
. Each contains 2 values. length/size= 2. Given below.
indexnameList = ['c_aa98efb4-630a-4eef-b51e-ba884635eehh_driver', 'c_aa98efb4-630a-4eef-b51e-ba884635eekk_driver']`
payloadList = [
{
"id": "d90b6782-0a94-4a0d-ab6a-42d95d47db40",
"version": "2.4",
"sequence": "1.0",
"event_id": "c21aebf8b235459180953d14bbf32027"
},
{
"id": "d90b6782-0a94-4a0d-ab6a-42d95d47db41",
"version": "2.5",
"sequence": "1.0",
"event_id": "3127eda13f93464c9ecc9dc7452a5c04"
}
]
I want to append the indexnameList each index value to the payloadList value. So using as below. But always getting the '0'th index value only after appending to the payloadList .
body = []
c=0
for entry in payloadList:
body.append({'index': {'_index': indexnameList[c], '_type': 'doc', '_id': entry['id']}})
body.append(entry)
response = es_client.bulk(body=body)
return {"statusCode" :200,
"message" : str(len(payloadList)) " objects inserted into opensearch.",
"open search response" :response,
"payloadList" : payloadList
}
Need solution -- How can i pass value of indexnameList[c] inside the for loop. So the each index value of indexnameList will get in the below line to append.
body.append({'index': {'\_index': **indexnameList\[c\]**, '\_type': 'doc', '\_id': entry\['id'\]}})
CodePudding user response:
You might wanna look into zip() which works like this:
list_a = [1, 2, 3]
list_b = ['a', 'b', 'c']
new_list = []
for a,b in zip(list_a, list_b):
new_list.append( (a,b) )
Of course it's more beautiful as list comprehension:
new_list = [ (a,b) for a,b in zip(list_a, list_b) ]
Anyway: you can of course also loop through multiple lists where one contains a dictionary and update that :).
Alternative approach:
for index, item in enumerate(list_a):
# gives you an index counting from 0 and the item
Last but not least: please try to optimize your code :D. pep8 and using SO code-blocks.
CodePudding user response:
If I am reading your question correctly, I think you are trying to add each element from the "indexnameList" to a respective key in each dictionary in the "payloadList". If this is what you are trying to do, you can iterate through the indexnameList and enumerate it, to utilize their indices, so as to reference that same index in the payloadList.
for n, i in enumerate(indexnameList):
payloadList[n]['index_name'] = i
If you were to print out the payloadList, it will now contain a new key called "index_name", which will contain the value of the indexnameList value, for each element.
I would also advise you to learn about data structures in python, particularly lists and dictionaries, as well as how to utilize for loops. If this isn't what you were trying to do, please let me know and give me more concise instructions so I can help you further.