I have a dictionary like below
[{
“a”: {
“uuid”: “4458”,
“created_at”: “2022-10-19 12:20”,
“source_platform”: “abc”,
“platform”: “UK”
},
“b”:[],
“c”: [],
“d”: [],
“f”: [],
“e”: [],
“g”: [],
“h”: [],
“i”: [],
“j”: {}
}]
and I need to return 'no_info' if the list of a key such as 'b' or 'j' is empty.
but when I use this function
def get_lead_first_platform(data: dict) -> str:
try:
if isinstance(data.get('b'), list):
if data.get('b')[0].get('ad_source'):
return data.get('b')[0].get('ad_source')
else:
return 'no_info'
except Exception as e:
print(f'{inspect.stack()[0][3]} -- {e}')
return None
it gives me this error get_lead_first_platform -- 'list' object has no attribute 'get'
CodePudding user response:
You need to do the empty check before accessing the list.
def get_lead_first_platform(data: dict) -> str:
try:
if isinstance(data.get('b'), list):
if len(data.get('b')[0]) > 0:
return data.get('b')[0].get('ad_source')
else:
return 'no_info'
except Exception as e:
print(f'{inspect.stack()[0][3]} -- {e}')
return None
CodePudding user response:
You do not "have a dictionary" as you stated. What you have here is a list with a dictionary within it. Hence if you pass it to your function you are actually calling .get()
on a list.
So data.get("b")
would be
[{
“a”: {
“uuid”: “4458”,
“created_at”: “2022-10-19 12:20”,
“source_platform”: “abc”,
“platform”: “UK”
},
“b”:[],
“c”: [],
“d”: [],
“f”: [],
“e”: [],
“g”: [],
“h”: [],
“i”: [],
“j”: {}
}].get("b")
Maybe try executing get_lead_first_platform(data[0])
.
Edit:
After fixing the error with .get()
you will run into an "index out of range" error with the statement data.get('b')[0]
if the list
"b" is empty.
CodePudding user response:
yes list has no attribute get you should try with join.