RDK
RDK

Reputation: 385

Looping through OrderedDict objects errors

I'm trying to learn how to manipulate python2.7 OrderedDict objects. I have an OrderedDict which was provided earlier in the program. I'm trying to understand its structure and at the same time understand how to manipulate this object and extract various elements and element values from the dictionary.

In the code below I demonstrate that the initial ordered dictionary object, finaldata, has one key ['models']. I create a new ordered dictionary, fdata_models, from finaldata using that key. And then a new ordered dictionary using one of the keys from fdata_models, etc.

Below you can see my test program and the output from the its experiments.

I have several questions, but the most pressing is why I can not loop through the dictionary objects within fdata_models?

After that question, I've tried the syntax "fdata_model = fdata_models[0]", instead of hard coding the key, ['models'], but that also throws an error. Is there a way to index, say the 3-rd occurance, within fdata_models without knowing its actual key value?

....
fdata_models = OrderedDict()
fdata_model = OrderedDict()
fdata = OrderedDict()
print("finaldata Keys are ", finaldata.keys())
fdata_key = finaldata.keys()
print("finaldata Key is ", fdata_key)
fdata_models = finaldata['models']
print("Number of ", fdata_key, " are ", len(fdata_models))
print("['Models'] Keys are ", fdata_models.keys())    
fdata_model = fdata_models['1']
print("Number of models['1'] are ", len(fdata_model))
print(" models['1'] keys are ",fdata_model.keys())
fdata_model = fdata_models['64110']
print("Number of models['64110'] are ", len(fdata_model))
print(" models['64110'] keys are ",fdata_model.keys())
for fdata in fdata_models:
    print("fdata['model']", " keys are ", fdata[0].keys())

('finaldata Keys are ', ['models']) ('finaldata Key is ', ['models'])

('Number of ', ['models'], ' are ', 4)

("['Models'] Keys are ", ['123', '110', '111', '112'])

("Number of models['123'] are ", 7)

("models['123'] keys are ", ['model', 'Mn', 'Md', 'Opt', 'Vr', 'SN', 'DA']) ("Number of models['110'] are ", 47) (" models['64110'] keys are ", ['model', 'MajorFWRev', 'MidFWRev', 'MinorFWRev', ...
'TimeZone', 'Date_year', 'Date_month', 'Date_Day', 'Time_hour', 'Time_minute', 'Time_second', ...]) Traceback (most recent call last): File /pgms/json.py", line 204, in print("fdata['model']", " keys are ", fdata[0].keys()) AttributeError: 'str' object has no attribute 'keys'

Thanks...RDK

Upvotes: 1

Views: 81

Answers (1)

glibdud
glibdud

Reputation: 7850

OrderedDicts work just like dicts in this respect. When you iterate over them, you get the keys.

for fdata in fdata_models:
    print("fdata['model']", " keys are ", fdata_models[fdata].keys())

(Also note that all three of your ... = OrderedDict() lines don't actually do anything useful, since you rebind fdata_models, fdata_model, and fdata again before you use them.)

Upvotes: 1

Related Questions