【问题标题】:Write a for loop that prints the Keys of 1 nested dictionary编写一个 for 循环,打印 1 个嵌套字典的键
【发布时间】:2019-02-22 00:29:04
【问题描述】:

1> 创建一个嵌套字典,其中包含您今年秋季和春季学期所学科目的科目编号。换句话说,您应该有一个包含 2 个键“Autumn”和“Spring”的字典,并且与这些键关联的值本身应该是字典,其中键是主题编号,值是主题名称。

2> 编写一个 for 循环,打印出你在秋季完成的科目数。

这就是我所拥有的

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)

但收到错误

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'

【问题讨论】:

  • 您想要识别您每个赛季参加的课程的数字吗?或者你每个赛季上过多少门课?

标签: python loops dictionary for-loop nested


【解决方案1】:

使用season.subjects 中的. 运算符,您正在尝试访问没有此类属性的season 对象的subjects 属性。您应该将 my_subjects.items() 返回的元组中第二项的值分配给单独的变量:

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

这个输出:

Autumn Subject Numbers: 37315, 34567

【讨论】:

  • 此代码仅返回主题数,而不是附加的主题号。
  • 秋季科目编号:2
  • 我明白了。当您说主题编号时,我以为您的意思是输出主题数量。我已经相应地更新了我的答案。
【解决方案2】:

试试这个

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)

【讨论】:

  • 秋季科目编号 秋季 37315 34567 秋季科目编号 春季 23456 45879
【解决方案3】:

这个怎么样?

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]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-09
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多