简体   繁体   中英

python updating each key value of dictionary in list

I have a dictionary in a list, and I am trying to iterate over the list and update dictionary key, value every after 10 seconds.

Example:

list = [{"id": 3, "status": "pending"}, {"id": 4, "status": "pending"}, {"id": 2, "status": "pending"}]

At a certain condition, I have another variable global_status = executing or blocked or completed based on global_status

if (global_status == executing ):
        output : [{"id": 3, "status": "routing"}, {"id": 4, "status": "pending"}, {"id": 2, "status": "pending"}]
    wait for 10 seconds
        output : [{"id": 3, "status": "completed"}, {"id": 4, "status": "routing"}, {"id": 2, "status": "pending"}]
    wait for 10 seconds
        output : [{"id": 3, "status": "completed"}, {"id": 4, "status": "completed"}, {"id": 2, "status": "completed"}]

Here I am iterating over the list, waiting for 10 seconds. Based on the global_status , update key, values of each dictionary separately in a sequential way.

I made two fixes for your code.

First: You must have fixed pattern to use for loop. I made an example pattern for you.

routing     pending     pending
completed   pending     pending

completed   routing     pending
completed   completed   pending

completed   completed   routing
completed   completed   completed

Second: You have to use two for loops to change each 'status' in each dictionary or it will change all of them.

import time
List = [{"id": 3, "status": "pending"}, {"id": 4, "status": "pending"}, {"id": 2, 
"status": "pending"}]
count = ['routing', 'completed'] # this is for your status

for i in List:
    for j in range(len(i)):
        i['status'] = count[j]
        print(List)
        time.sleep(10)

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