I have a attribute of type 'List of maps' in my dynamodb. e.g. List = [{key1: value1},{key2: value2},{key3:value3},...] I want to update the list (from my python script) with current_key to add a new key or replace the value if the current_key is already present.
1 Answers
0
votes
To illustrate the code below better, I've chosen to change your {key1:value1}
to strings. Functionally, when you are calling the add_to_datalist
function, there should be no difference.
def add_to_datalist(datalist, key, value):
check = 0
#check is needed to ensure the if condition after the for loop can trigger
for datadict in datalist:
if key in datadict.keys():
datadict[key] = value
check = 1 #turn off check if a key matching is found
if check == 0:
datalist.append({key:value})
return datalist
datalist = [{'key1':'value1'},{'key2':'value2'},{'key3':'value3'}]
key1 = 'key333'
value1 = 'value999'
datalist = add_to_datalist(datalist, key1, value1)
key2 = 'key2'
value2 = 'valueNEW2'
datalist = add_to_datalist(datalist, key2, value2)
print (datalist)
#[{'key1': 'value1'}, {'key2': 'valueNEW2'}, {'key3': 'value3'}, {'key333': 'value999'}]