mercredi 19 mai 2021

Is there a way to loop through python dictionaries only with a specific key-value pair?

I'm not very experienced with Python + dictionary objects so I think I may be trying to go about this task in the wrong way...

The goal is to search through a database for files with a certain filetype and then return the files that are missing a string in their filename. The files are dict objects which are accessible through scans (also dict objects) which are accessible through sessions (also dict objects!).

I'm testing by looping through the scans for just one session and this is what is working currently:

for scan in session_data[1539].scans.values():
    for file in scan.files.values():
        if file.file_format == "NIFTI" and "*input_*" not in file._cache['id']:
            print(scan)
            print(file)

The problem is: to every one file of the type I am interested in, there are thousands of files with a different file type that I'm not interested in that are being looped through and slowing down the process to the point this method will not work when I add looping through all the sessions. Is there some way for me to loop through only the files with file_format : NIFTI and ignore the others? Something like this (but functional, lol):

for scan in session_data[1539].scans.values():
    for file in scan.files['file_format':'NIFTI'].values():
        if "*input_*" not in file._cache['id']:
            print(scan)
            print(file) 

These are the properties and methods for the files dictionary:

print(dir(scan_data[1].files[1]))
['SECONDARY_LOOKUP_FIELD', '_CONTAINED_IN', '_DISPLAY_IDENTIFIER', '_HAS_FIELDS', '_XSI_TYPE', '__abstractmethods__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '__xsi_type__', '_abc_impl', '_cache', '_caching', '_fieldname', '_fields', '_overwrites', '_parent', '_path', '_uri', '_xnat_session', 'caching', 'cat_id', 'clearcache', 'collection', 'data', 'del_', 'delete', 'digest', 'download', 'download_stream', 'external_uri', 'fieldname', 'file_content', 'file_format', 'file_size', 'file_tags', 'full_data', 'fulldata', 'fulluri', 'get', 'get_object', 'id', 'logger', 'mset', 'open', 'parent', 'path', 'query', 'set', 'size', 'uri', 'xnat_session', 'xpath']

Thank you :)

Aucun commentaire:

Enregistrer un commentaire