I want to create an if-else condition on dictionaries with missing keys. Such that, if the key is missing then append the value None
, otherwise append the data when it exists.
However, this approach would stop with an error as when the key does not exist it seems to not return True or False
.
For example:
df = [{'data':'test', 'videos':5, 'likes':4}, {'data':'test','likes':4}]
videos = []
for i in df:
if i['videos']:
videos.append(i)
elif i['videos'] is not True:
videos.append('None')
Output:
{'data': 'test', 'videos': 5, 'likes': 4}
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/var/folders/dr/9wh_z8y10fl79chj86pq7knc0000gn/T/ipykernel_3180/3991749010.py in <module>
1 df = [{'data':'test', 'videos':5, 'likes':4}, {'data':'test','likes':4}]
2 for i in df:
----> 3 if i['videos']:
4 print(i)
5 elif i['videos'] is not True:
KeyError: 'videos'