Concatenate OR conditional expressions from list to "|"
<p>This probably is a python lang related question, not precisely of boto3 lib:</p>

<p>That query works:</p>

<pre><code>matches = table.query(
    IndexName="status-date-index",
    KeyConditionExpression=Key('status').eq('next'),
    FilterExpression=Attr('teams').contains('a') | Attr('teams').contains('b') | Attr('teams').contains('c')
)
</code></pre>

<p>But I will have a varible list  <code>["a", "b", "c", ...N]</code> and need to convert them to</p>

<pre><code>filter_expression = Attr('teams').contains('a') | Attr('teams').contains('b') | Attr('teams').contains('c') | ...N
</code></pre>

<p>any ideas how to do it in python? or maybe I need to do a better FilterExpression for that case?</p>

<p><a href="http://boto3.readthedocs.io/en/latest/_modules/boto3/dynamodb/conditions.html" rel="nofollow">boto3.dynamodb.conditions.Attr reference.</a></p>

<p>You can use <a href="https://docs.python.org/library/functools.html#functools.reduce" rel="nofollow"><code>functools.reduce</code></a> on the list of items produced by <code>contains</code> (which I assume to be of type <code>ConditionBase</code>), with the <a href="https://docs.python.org/2/library/operator.html#operator.or_" rel="nofollow"><code>or_</code> operator</a>.  You can also couple that with <a href="https://docs.python.org/library/functools.html#functools.map" rel="nofollow"><code>functools.map</code></a> on the strings since you have a pile of similar inputs.  Consider this much simplified example:</p>

<pre><code>&gt;&gt;&gt; from functools import map
&gt;&gt;&gt; from functools import reduce
&gt;&gt;&gt; from operator import or_
&gt;&gt;&gt; values = ['9', '3', '7', '32']
&gt;&gt;&gt; map(int, values)
[9, 3, 7, 32]
&gt;&gt;&gt; reduce(or_, map(int, values))
47
</code></pre>

<p>Exact equivalent to</p>

<pre><code>&gt;&gt;&gt; 9 | 3 | 7 | 32
47
</code></pre>

<p>To further simplify the generation of <code>Condition</code> objects from <code>Attr(field).contains(value)</code>, a list of 2-tuple can be constructed, like so (based on your original question) through list-comprehension:</p>

<pre><code>raw_conditions = [
    ('teams', 'a'),
    ('b', 'cali'),
    ('teams', 'c'),
]

conditions = [Attr(field).contains(value) for field, value in raw_conditions]
filter_expression = reduce(or_, conditions)
</code></pre>

python amazon-dynamodb