Search code examples
pythonpandasdataframedictionarydictionary-comprehension

Python dict comprehension error while extracting data from dataframe


Dict comprehensions with conditions

I have a Pandas dataframe from where I want to extract data to a dictionary. 'addresses' is a dict where keys are the level 0 indices of the dataframe (but not all of them). I want to do such operation:

dfl = df1.loc[df1.tagkey.isin(['building:levels'])]
levels = {k : dfl.at[k, 'tagvalue'] for k in addresses.keys() if k in dfl.index else 0}

But I receive an error of invalid syntax. Don't understand why


Solution

  • You can't use a ternary in the right part of the comprehension:

    {… for … in … if … else …}
    

    You can only do it in the left part:

    {… if … else … for … in …}
    

    In your case this should be:

    levels = {k : dfl.at[k, 'tagvalue'] if k in dfl.index else 0
              for k in addresses.keys()}