Reputation: 19
I have a dictionary which looks like this,
{'023': {'ARTERIAL': {'Age': '043Y'},
'PORTAL': {'Age': '043Y'},
'VENOUS': {'Age': '043Y'}},
'024': {'ARTERIAL': {'Age': '048Y'},
'PORTAL': {'Age': '048Y'},
'VENOUS': {'Age': '048Y'}}}
I have set this up using this ,
data_dict={}
for folders in os.listdir(new_path):
for AVP in os.listdir(os.path.join(new_path, folders)):
for files in os.listdir(os.path.join(new_path, folders, AVP)):
file = dicom.read_file(os.path.join(new_path, folders, AVP, files))
Name = file.Name
Age = file.Age
at = file.AcquisitionNumber
data_dict.setdefault(folders, {}).setdefault(AVP,{}).setdefault('Age',file.Age)
break
Now along with Age i would like to add more key value items to the age dictionary ,Something like this
{'023': {'ARTERIAL': {'Age': '043Y','number': 43, 'time':12:00},
'PORTAL': {'Age': '043Y','number': 3, 'time':2:00},
'VENOUS': {'Age': '043Y','number': 93, 'time':1:00}},
i have tried
data_dict.setdefault(folders, {}).setdefault(AVP,{}).setdefault('Age',file.Age).setdefault(file.AcquisitionNumber, file.AcquisitionNumber)
which gives me
AttributeError: 'str' object has no attribute 'setdefault'
Any suggestions on how i can add more key value pairs will be helpful, Thanks in advance
Upvotes: 1
Views: 53
Reputation: 780974
setdefault
returns the value of the dictionary element, either the one that was already there or the default you provided. The first two setdefault()
calls return the nested dictionaries, but the last one returns file.Age
, which is a string.
Assign the last dictionary to a variable and then set the values you want in it:
d = data_dict.setdefault(folders, {}).setdefault(AVP,{})
d['Age'] = file.Age
d['number'] = file.AcquisitionNumber
Upvotes: 3