Python Forum

Full Version: Loop Dict with inconsistent Keys
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello guys,

I'm 4 days old with Python and Flask, I have a FlaskForm which works pretty well. This form has FieldList with BooleanField in. And I'm not sure how to process the result after I submit the form.

When the form is submitted, I get this Dict:

newparts={
'0': {'invid': '2812', 'oriqty': '6', 'qty': '6', 'checkbox': 'y'}, 
'1': {'invid': '2813', 'oriqty': '4', 'qty': '4'}, 
'2': {'invid': '2810', 'oriqty': '2', 'qty': '2'}, 
'3': {'invid': '2811', 'oriqty': '1', 'qty': '1', 'checkbox': 'y'}
}
As you see, the checkbox key, only exist in the item 0 and 3

My end goal is to find only the entries where the checkbox is equal to 'y', and return the invid value

I tried a loop like this one:
for p_id in newparts:
    if newparts[p_id]['checkbox'] == 'y':
        print(p_id)
but the error I get is

Error:
Traceback (most recent call last): File "main.py", line 10, in <module> if newparts[p_id]['checkbox'] == 'y': KeyError: 'checkbox'
Thank you for your help
newparts={
'0': {'invid': '2812', 'oriqty': '6', 'qty': '6', 'checkbox': 'y'}, 
'1': {'invid': '2813', 'oriqty': '4', 'qty': '4'}, 
'2': {'invid': '2810', 'oriqty': '2', 'qty': '2'}, 
'3': {'invid': '2811', 'oriqty': '1', 'qty': '1', 'checkbox': 'y'}
}

for p_id in newparts:
    if 'checkbox' in newparts[p_id] and newparts[p_id]['checkbox'] == 'y':
        print(p_id)
Output:
0 3