I have and array with nested objects that i want to iterate through and pass the values to a string. I also want to concat the values with another string, as in the example. Im used to JavaScript and i know that this can be done with a map method there. But i'm struggling to find an equivalent in Python.
So my goal is to dynamically pass the values to the string after iterating the array.
objExpression = [
{
'name': 'name',
'value': id,
'type': 'S',
},
{
'name': 'brandCode',
'value': brandCode,
'type': 'S',
},
...
]
UpdateExpression='SET #' objExpression[0]['name'] '= :'objExpression[0]['name'] ',' '#' objExpression[1]['name'] '= :' objExpression[2]['name'] ...'
#Expected output
UpdateExpression='SET #name = :name, #brandCode = :brandCode'
CodePudding user response:
Probably something like this:
"SET " ", ".join(f"#{item['name']} = :{item['name']}" for item in objExpression)
which gives
'SET #name = :name, #brandCode = :brandCode'
The above futures:
- a list comprehension:
[item for item in objExpression]
. - f-strings:
f"#{item} = :{item}"
- f-strings with a dict lookup:
f"#{item['name']}"
- a string concatenation with
", ".join(list_of_strings)
.
(note: the list_of_strings looks like it's missing its square brackets, []
, from the first bullet point. I have turned it into a generator expression, marked by the ()
, which you can do for some cases. In this cases, the ()
actually mark the method call of join()
, where you can fit a generator expression inside of (the result is an iterable of strings, which works fine for .join()
).
CodePudding user response:
This may work for you:
objExpression = [
{
'name': 'name',
'value': 1,
'type': 'S',
},
{
'name': 'brandCode',
'value': 123,
'type': 'S',
}
]
UpdateExpression = 'SET '
tmpExpression = []
for exp in objExpression:
tmpExpression.append(f"#{exp['name']} = :{exp['name']}")
UpdateExpression = ', '.join(tmpExpression)
The output:
'SET #name = :name, #brandCode = :brandCode'