adplus-dvertising

Python dictionary: How to assign a default value to every Null entry found

Asked 3 months ago
Viewed 14 times

I have a list like

ner_issue_lst = [
    'device no power',
    'speaker not work',
    'charge port not work laptop plug charger',
    '',
    'keyboard not functional',
    '',
    ' ',
    'system not charge'
]

I want to assign a default value where I encounter the null or empty. My current code is like below. The if condition is working fine for me. In the else condition whenever I encounter null I should be able to assign a default value like ('Empty Item | Null', 5.9999) to each occurrence of null value in the dictionary. Its the syntax I am struggling with.

# Check if the string is empty or contains spaces only and define a default value to it 
res_final = {}
default_val = ('Empty Item | Null', 5.9999)
for index_val, row_val in enumerate(ner_issue_lst):
    if row_val and row_val.strip():
        print('String is neither empty nor blank')
        embed_query_val = model.encode([row_val])
        distance, faiss_value = index.search(embed_query_val, k)
        res_final[row_val] = [labels_lst[index_val] for index_val in faiss_value[0]][
        0
    ], distance.item()
    else:
        print('String is either None or Empty or contain spaces only')
        res_final[row_val] = default_val # This is not working # # correct syntax required here #

values_lst = list(res_final.values())
faiss_label_lst = [list(tup) for tup in values_lst]
if len(ner_issue_lst) != len(faiss_label_lst):
    print("Input issue list and Output label list must have the same length")

asked 3 months ago

Correct Answer

If you want to check if a string contains only whitespace, use str.isspace:

>>> ner_issue_lst = [
...     'device no power',
...     'speaker not work',
...     'charge port not work laptop plug charger',
...     '',
...     'keyboard not functional',
...     '',
...     ' ',
...     'system not charge'
... ]
>>> [i if i and not i.isspace() else 'Empty Item | Null' for i in ner_issue_lst]
['device no power', 'speaker not work', 'charge port not work laptop plug charger', 'Empty Item | Null', 'keyboard not functional', 'Empty Item | Null', 'Empty Item | Null', 'system not charge']
answered 3 months ago