Will Lobb
Will Lobb

Reputation: 9

Write a for loop that prints the Keys of 1 nested dictionary

1> Create a nested dictionary which contains the subject numbers for the subjects you're doing this year in both the Autumn and Spring semesters. In other words, you should have a dictionary with 2 keys, "Autumn" and "Spring", and the values associated with these keys should themselves be dictionaries where the keys are the subject numbers and the values the names of the subjects.

2> Write a for loop that prints out the numbers of the subjects you did in Autumn.

This is what i have

my_subjects = {"Autumn": {37315:"Data", 34567:"Sci"}, "Spring": {23456:"Eng", 45879:"Math"}}

for season, season.subjects in my_subjects.items():
    print("\n Autumn Subject Numbers", season)

    for key in season.subjects:
        print(key)

but receive an error

AttributeError                            Traceback (most recent call last)
<ipython-input-208-b1fceae351e6> in <module>()
      5 
      6 
----> 7 for season, season.subjects in my_subjects.items():
      8     print("\n Autumn Subject Numbers", season)
      9 

AttributeError: 'str' object has no attribute 'subjects'

Upvotes: 1

Views: 59

Answers (3)

blhsing
blhsing

Reputation: 107115

With the . operator in season.subjects you are trying access the subjects attribute of the season object, which has no such attribute. You should instead assign the value of the second item in the tuples returned by my_subjects.items() to a separate variable:

for season, subjects in my_subjects.items():
    if season == 'Autumn':
        print("Autumn Subject Numbers:", ', '.join(map(str, subjects)))

This outputs:

Autumn Subject Numbers: 37315, 34567

Upvotes: 2

vash_the_stampede
vash_the_stampede

Reputation: 4606

How about this ?

new_dict = {}

for k, v in my_subjects.items():
    for x, z in v.items():
        if k not in new_dict:
            new_dict[k] = [x]
        else:
            new_dict[k].append(x)
print(new_dict)
{'Autumn': [37315, 34567], 'Spring': [23456, 45879]}

Upvotes: 0

agrojas
agrojas

Reputation: 1

Try with this

my_subjects = {"Autumn": {37315:"Data", 34567:"Sci"}, "Spring": {23456:"Eng", 45879:"Math"}}

for season, data in my_subjects.items():
    print("\n Autumn Subject Numbers", season)

    for key in data:
        print(key)

Upvotes: 0

Related Questions