【问题标题】:iterating nested dictionaries using for loop in python在python中使用for循环迭代嵌套字典
【发布时间】:2021-12-03 14:04:48
【问题描述】:

这是我的 json 文件,其中包含嵌套字典中的示例数据,如下所示

data = {
    'school': {
        'name': 'abc',
        'class': {
            'firstclass': {'teacher': 'b', 'students': '10'},
            'secondclass': {'teacher': 'c', 'students': '25'},
        }, 'city': 'x'},
    'college': {
        'name': 'def',
        'class': {
            'firstclass': {'teacher': 'd', 'students': '9'},
            'secondclass': {'teacher': 'e', 'students': '65'},
        }, 'city': 'y'},
    'university': {
        'name': 'ghi',
        'class': {
            'firstclass': {'teacher': 'f', 'students': '55'},
            'secondclass': {'teacher': 'g', 'students': '22'},
        }, 'city': 'z'}
}

我的输出应该是这样的:

'teacher':'b','students':'10'
'teacher':'d','students':'9'
'teacher':'f','students':'55'

这是我在 for 循环中的代码:

for id in data:
    for j in data[id]:
        print(j  ,"="  , data[id][j])

我没有超出预期的输出。 如何获得如上的准确输出。

【问题讨论】:

  • 您正在显式打印"=",这甚至不在您的预期输出中?!
  • 另外,请发布可以逐字复制的数据结构。你的data 不是有效的dict
  • for j in data[id]['class']

标签: json python-3.x pandas dictionary


【解决方案1】:

这可能会让你朝着正确的方向前进:

for v in data.values():
    for dct in v["class"].values():
        print(", ".join(map("=".join, dct.items())))
    
teacher=b, students=10
teacher=c, students=25
teacher=d, students=9
teacher=e, students=65
teacher=f, students=55
teacher=g, students=22

【讨论】:

  • 如果我只想从每个班级获得一等或二等
  • 哪个先?您想要的输出与此答案中的输出一样有 6 个键值对?
  • 是的,我得到了准确的输出,但如果我只想从学校、学院和大学的班级获得一等或二等的字典,比如学校的一等、大学的一等和大学的一等,该怎么办?数据值
  • 那么你必须明确地访问这些组合键。
  • 好的,谢谢,接受你的回答
猜你喜欢
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
相关资源
最近更新 更多