简体   繁体   中英

How to solve this loop to print all the values?

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)


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)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM