Python Forum
Loop Dict with inconsistent Keys - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Loop Dict with inconsistent Keys (/thread-36286.html)



Loop Dict with inconsistent Keys - Personne - Feb-05-2022

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


RE: Loop Dict with inconsistent Keys - Larz60+ - Feb-05-2022

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