Home > Back-end >  How to solve this loop to print all the values?
How to solve this loop to print all the values?

Time:12-24

It should print 5,3.33 but it is only printing 3 ?How to print both values

bucket_data22={1: {'key': 'Security Awareness Overview', 'value': 20, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 155}, 
             2: {'key': 'Security Awareness Overview', 'value': 0, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 159}, 
             3:  {'key': 'Security Awareness Overview', 'value': 30, 'start_date': '24/09/2021', 'end_date': '27/09/2021', 'id': 174}}
completed_data={155: 1, 174: 1}
for z in completed_data:
    print(z)
for i in bucket_data22:
    if (bucket_data22[i]['id']==z):
        print((completed_data[z]/bucket_data22[i]['value'])*100)


CodePudding user response:

It works now:

 bucket_data22={1: {'key': 'Security Awareness Overview', 'value': 20, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 155}, 
                 2: {'key': 'Security Awareness Overview', 'value': 0, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 159}, 
                 3:  {'key': 'Security Awareness Overview', 'value': 30, 'start_date': '24/09/2021', 'end_date': '27/09/2021', 'id': 174}}

completed_data={155: 1, 174: 1}

for z in completed_data:
    for i in bucket_data22:
        if (bucket_data22[i]['id']==z):
            print((completed_data[z]/bucket_data22[i]['value'])*100)

CodePudding user response:

z has the last value of completed_data, thus you only get one match (the id 174).

You should test bucket_data22[i]['id'] in completed_data

for i in bucket_data22:
    if (bucket_data22[i]['id'] in completed_data):
        print((completed_data[z]/bucket_data22[i]['value'])*100)

Output:

5.0
3.3333333333333335

CodePudding user response:

It appears that the second loop only begins after the first one is already finished.
Therefore, the second loop always gets the same value of 'z', which equals 174.
If you want to iterate all the values of 'z', you must move the second loop into the first loop.

bucket_data22={1: {'key': 'Security Awareness Overview', 'value': 20, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 155}, 
         2: {'key': 'Security Awareness Overview', 'value': 0, 'start_date': '13/07/2021', 'end_date': '12/08/2021', 'id': 159}, 
         3:  {'key': 'Security Awareness Overview', 'value': 30, 'start_date': '24/09/2021', 'end_date': '27/09/2021', 'id': 174}}
completed_data={155: 1, 174: 1}

for z in completed_data:
    for i in bucket_data22:
        if (bucket_data22[i]['id']==z):
          print((completed_data[z]/bucket_data22[i]['value'])*100)
  • Related