skip to Main Content

I wrote a script which updates some fields in a database via an API.

        fields = [{
              "fieldId": "101",                                       
              "fieldValues": [{"value": df["A"].item()}]},
                {   
              "fieldId": "102",                                       
              "fieldValues": [{"value": df["B"].item()}]},
                {   
              "fieldId": "103",                                        
              "fieldValues": [{"value": df["C"].item()}]},
                {   
              "fieldId": "104",                                        
              "fieldValues": [{"value": df["D"].item()}]},
                {   
              "fieldId": "105",                                        
              "fieldValues": [{"value": df["E"].item()}]
              }]

Afterwards I do something like update = update_object(fields = fields) to update the fields
I’d like to create fields more dynamically, meaning that a specific fieldId/fieldValues is only part of fields if (e.g.) df["E"] is not null.

How can I realize that?

2

Answers


  1. Maybe something like this?

    import pandas as pd
    
    df = pd.DataFrame([[42, None]], columns=['A', 'B'])
    print(df)
    

    prints

         A     B
    0   42  None    
    

    and then

    id_key_pairs = [
        ('101', 'A'),
        ('102', 'B')
    ]
    
    fields = [
        {
            'fieldId': field_id,
            'fieldValues': [{'value': df[k].item()}]
        } for field_id, k in id_key_pairs if df[k].item() is not None
    ]
    print(fields)
    

    prints

    [{'fieldId': '101', 'fieldValues': [{'value': 42}]}]
    
    Login or Signup to reply.
  2. This would be a nice case for a list comprehension! In your case, you could use something like this:

    df_key_map = {101: “A”, 102: “B”, (etc…)}
    fields = [
      {
        “fieldId”: id,
        “fieldValues”: [{“value”: df[key].item()}]
      }
      for id, key in df_key_map.items()
      if df[key].item() is not None
    
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search