Home > Net >  Looping through a dictionary that has multiple None value
Looping through a dictionary that has multiple None value

Time:10-25

I have a dataframe that has a multivalued column. This column has a dictionary inside a list. It may be that in some line it comes as None or the dictionary inside the list. The idea is to go through this column and bring only what is not null, in this case what is in the 'optionText' key.

For this, I transformed this column into a dictionary to process the data, the entire list that has several dictionaries that have the 'optionText' key must be concatenated into a single string or if there is any value in 'optionText' I also need to return, however, when I return the value I get an error message.

AttributeError: 'NoneType' object has no attribute 'get'

Here is an example of the column transformed into a dictionary and the code that handles it:

{0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None, 10: None, 11: None, 12: None, 13: None, 14: None, 15: None, 16: [{'optionId': 18281008, 'optionText': 'SOMETHING', 'optionValue': 0}], 17: None, 18: None, 19: None, 20: None, 21: None, 22: None, 23: None, 24: None, 25: None, 26: None, 27: None, 28: None, 29: None, 30: None, 31: None, 32: None, 33: None, 34: [{'optionId': 18281060, 'optionText': 'SOMETHING', 'optionValue': 0}], 35: [{'optionId': 18281262, 'optionText': 'SOMETHING', 'optionValue': 0}], 36: None, 37: None, 38: None, 39: None, 40: None, 41: None, 42: None, 43: None, 44: None, 45: None, 46: None, 47: None, 48: None, 49: None, 50: [{'optionId': 18281108, 'optionText': 'SOMETHING', 'optionValue': 0}], 51: [{'optionId': 18231299, 'optionText': 'SOMETHING', 'optionValue': None}, {'optionId': 18231300, 'optionText': 'SOMETHING', 'optionValue': None}, {'optionId': 18231301, 'optionText': 'SOMETHING', 'optionValue': None}]}
dict = df_itens.selectedOptions.to_dict()

def treatmentSelectedOptions(dict):
    texto = ''
    for i in range(len(dict)):
        try:
            if( i < len(dict)-1 ):
                texto = texto   dict[i].get('optionText', '')   ", "
            else:
                texto = texto   dict[i].get('optionText', '')
        except KeyError:
            print('key does not exist in dict')
            dict[i] =  []
        
    return texto

CodePudding user response:

This will return a new dict b if for every key in the dict a there is a value associated with the key:

b = {k: a.get(k) for k in a if a.get(k) is not None}

Modifying this for your example, you can add an additional lookup to check whether a certain element associated with this key fulfills a certain condition. In this case I check whether "optionText" of the first element in the list not None, but you can modify this to your needs, then join the values together:

b = {k: a.get(k)[0].get("optionText") for k in a if a.get(k) is not None and a.get(k)[0].get("optionText") is not None}
out = ", ".join(list(b.values()))
  • Related