0

I need to collect list of conditional elements to dataframe query, I manage to create it as below:

column = ['TotalCharges',  'gender']
equal = ['>', '==']
condition = [ 20, 'F']
query = ' & '.join(f'{i} {j} {repr(k)}' for i, j, k in zip(column, equal, condition))

So Query output:

TotalCharges > 20 & gender == 'F'

Which is the required and correct ,

Im curious how to achieve same thing using dictionary holds list, meaning

df_query_params =  {"column":[],"equal":[],"condition":[]}
df_query_params["column"] = ['TotalCharges',  'gender']
df_query_params["equal"] =  [ '>', '==']
df_query_params["condition"] = [20, 'F']

I tried similar approach, with df_query_params.keys() and also df_query_params.items() but it doesn't work,

The things that makes me little lost with list comprehension is that i don't know how to "gradually" add more nested elements,

wjandrea
  • 28,235
  • 9
  • 60
  • 81
AviC
  • 354
  • 1
  • 5
  • 15
  • Where's the list comprehension? I see a generator expression and some list literals, but no list comp. – wjandrea Jul 11 '21 at 15:51

2 Answers2

1

Well, if you just want the same query using comprehension for the given dictionary, one way would be to iterate through the values of the dictionary using zip, and join in similar fashion.

>>> ' & '.join(f'{i} {j} {repr(k)}' for i,j,k in zip(*df_query_params.values()))
"TotalCharges > 20 & gender == 'F'"
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
1

You just need to swap out the bare names.

query = ' & '.join(
    f'{i} {j} {repr(k)}'
    for i, j, k in
    zip(
        df_query_params["column"],
        df_query_params["equal"],
        df_query_params["condition"])
    )
wjandrea
  • 28,235
  • 9
  • 60
  • 81