python: nested list of dictionaries

Python's dictionary { } stores data in the form of key-value pairs. You can access the values ​​stored in the dictionary by keys but not by subscripts. A dictionary can contain almost any variable, dictionary, sequence, or tuple. The same goes for numbers.

Python's list [ ] is different from a dictionary. The list stores the content by a single element, and the elements are accessed by subscript.

The implementation of the python dictionary nested list is {key1:[ ] , key2:[ ] ,...}

Among them, the append() method is used to add a new object at the end of the list. The Python dictionary setdefault() function is similar to get(), if the key does not exist in the dictionary, it will add the key and set the value to the default value. The Python dictionary in operator is used to determine whether the key exists in the dictionary, and returns true if the key is in the dictionary dict, otherwise returns false. (python2 or has.key method)

A result statistics to be implemented recently uses this method to implement statistics on different IDs.

code show as below:

#Create a dictionary 
for id, file in enumerate(img):

    if file.find('gt')==-1:
        predict=file
        label=img[id+1]
        label_path = os.path.join(root, label)
        predict_path = os.path.join(root, predict)
        id = predict.split('_')[0]
        if patientid in dict:
            dict[id].append(label_path)
            dict[id].append(predict_path)
        else:
            dict.setdefault(patientid,[])
            dict[id].append(label_path)
            dict[id].append(predict_path)

 

In the follow-up, you can read the key in the dict in a loop, and then read the list in a loop through dict[key].

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324925603&siteId=291194637