循环遍历具有多个None值的字典



我有一个数据帧,它有一个多值列。此列的列表中有一个词典。可能是在某行中,它显示为None或列表中的dictionary。我们的想法是浏览这一列,只显示不为null的内容,在本例中是"optionText"键中的内容。

为此,我将此列转换为一个字典来处理数据,具有多个具有"optionText"键的字典的整个列表必须连接到一个字符串中,或者如果"optionText"中有任何值,我也需要返回,但是,当我返回值时,我会收到一条错误消息。

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

下面是一个转换为字典的列的示例以及处理它的代码:

{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

如果dict a中的每个键都有一个与该键相关的值,则这将返回一个新的dictb

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

对于您的示例进行修改,您可以添加一个额外的查找来检查与该键关联的某个元素是否满足某个条件。在这种情况下;optionText"列表中第一个元素的值不是None,但您可以根据需要修改它,然后将值连接在一起:

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()))

最新更新