Python Forum
Loop Dict with inconsistent Keys
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Loop Dict with inconsistent Keys
#1
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
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Read csv file with inconsistent delimiter gracenz 2 1,208 Mar-27-2023, 08:59 PM
Last Post: deanhystad
  Inconsistent loop iteration behavior JonWayn 2 1,007 Dec-10-2022, 06:49 AM
Last Post: JonWayn
  ValueError: Found input variables with inconsistent numbers of samples saoko 0 2,485 Jun-16-2022, 06:59 PM
Last Post: saoko
  Python3 for loop over a dict ogautier 3 1,395 Feb-25-2022, 10:17 AM
Last Post: Larz60+
  Updating nested dict list keys tbaror 2 1,294 Feb-09-2022, 09:37 AM
Last Post: tbaror
  Inconsistent counting / timing with threading rantwhy 1 1,775 Nov-24-2021, 04:04 AM
Last Post: deanhystad
  Inconsistent behaviour in output - web scraping Steve 6 2,571 Sep-20-2021, 01:54 AM
Last Post: Larz60+
  Found input variables with inconsistent numbers of samples: [1000, 200] jenya56 2 2,911 Sep-15-2021, 12:48 PM
Last Post: jenya56
  Packages inconsistent warning during hdbscan install Led_Zeppelin 0 1,934 Aug-31-2021, 04:10 PM
Last Post: Led_Zeppelin
  Create Dict from multiple Lists with duplicate Keys rhat398 10 4,089 Jun-26-2021, 11:12 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020