简体   繁体   中英

python set dict not exist, how can I handle it?

import SimpleITK as sitk

reader = sitk.ImageFileReader()
reader.SetFileName(filePath)
reader.ReadImageInformation()
img = reader.Execute()

meta = {
    "a": reader.GetMetaData('0'), <- if not exist return 'undeinfed'
    "b": reader.GetMetaData('1'),
    "c": reader.GetMetaData('2'),
}

I am javascript developer. I want to set meta dict and it shows error which is 'Key '0' does not exist'.

It can be not exist how can I set meta in this case?

From the docs , the ImageFileReader class has a HasMetaDataKey() boolean function. So you should be able to do something like this:

meta = {
    "a": reader.GetMetaData('0') if reader.HasMetaDataKey('0') else 'undefined',
    "b": reader.GetMetaData('1') if reader.HasMetaDataKey('1') else 'undefined',
    "c": reader.GetMetaData('2') if reader.HasMetaDataKey('2') else 'undefined',
}

And you could do in one (long) line:

meta = {m: reader.GetMetaData(k) if reader.HasMetaDataKey(k) else 'undefined'
        for m, k in zip(['a', 'b', 'c'], ['0', '1', '2'])}

you can use default dict

from collections import defaultdict
d = defaultdict(lambda : 'xx') #<- Whatever value you want
d[10] #no value passed value automatically assinged to xx
d[11]=12 #value 12 assinged
#to get value you can use d.get(key)
print(d[10]) #prints 'xx'
print(d)

outputs

defaultdict(<function <lambda> at 0x000001557B4B03A8>, {10: 'xx', 11: 12})

you get the idea you can modify according to your need

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