python dictionary iteration for data frame filtering with multiple conditions
<p>I am basically trying to build basic search engine that returns results based on a parsed query.</p>

<p>I have a dictionary that is user generated based on parsed input from their string:</p>

<pre><code>input = {âcolorâ: [âblackâ], âmakeâ: [âhondaâ], âtypeâ: [ââ]}
</code></pre>

<p>I am then trying to use that input, to do a search and filter of a dataset (which I am currently storing as a pandas dataframe, so please advise if this is also not optimal).</p>

<pre><code>list(df.column.values) = make,type,color,mpg,year

honda,coupe,red,32,2014
bmw,suv,black,21,2012
honda,suv,black,24,2015
vw,sedan,black,31,2016
</code></pre>

<p>I need to iterate over the valid values of my input dictionary (notice that âtypeâ doesnât have a value) and filter based on what the user entered in, âcolorâ and âmakeâ). Sometimes they might include the type and leave out the color, etc. so I might never have a value for every key in my dictionary;</p>

<p>Sudo code:</p>

<pre><code>for each valid value in my input dictionary:
    filter df by appropriate_column=appropriate_value
</code></pre>

<p>So given my input example, I would filter my df down to only entries that were âblackâ and made by âhondaâ.</p>

<p>Let <code>d</code> be your dict, then:</p>

<pre><code>cond = [df[k].apply(lambda k: k in v if v != [''] else True) for k, v in d.items()]
cond_total = functools.reduce(lambda x, y: x &amp; y, cond)
print(df[cond_total])
</code></pre>

<p>Output:</p>

<pre><code>    make type  color  mpg  year
2  honda  suv  black   24  2015
</code></pre>

python pandas dictionary