【问题标题】:How to print items from a dictionary when multiple values share the same key当多个值共享同一个键时如何从字典中打印项目
【发布时间】:2023-04-01 01:58:01
【问题描述】:

我在下面有一本字典,我正在尝试打印某一天的日期。但是,我收到了KeyError

{
 'length': 601,
 'maxPageLimit': 2500,
 'totalRecords': 601,
 'data': [{'date': '2021-12-13', 'newCases': 97},
          {'date': '2021-12-12', 'newCases': 64},
          {'date': '2021-12-10', 'newCases': 108}, 
          {'date': '2021-12-09', 'newCases': 129}]

}

例如,我希望能够仅打印 2021-12-13 和 97

【问题讨论】:

  • 您好,对于社区来说,证明您也在致力于解决您的问题非常重要。做到这一点的最好方法是包含您目前拥有的基于 text 的代码版本,即使它并不完全正确。根据您的输入,查看您期望的输出可能会有所帮助。

标签: python-3.x dictionary key


【解决方案1】:

日期在您的程序中用作值,因此您需要使用某种循环来访问所需的日期。

for date in d['data']:
    if date['date'] == foo:
        # do your processing

【讨论】:

    【解决方案2】:

    按照目前的设置,您拥有最顶层的字典,其中包含以下键:长度、maxPage、TotalyRecords 和数据。然后在数据内部,你有一个包含 2 个索引的列表,每个索引都是它自己的字典。

    如果您想获取 12 月 13 日的字典,那就是:

    dict['data'][0] # First we go to the "data" key and get that. Then inside of the 
                    data key we get index 0, which is {'date': '2021-12-13', 'newCases': 97}
    

    例如,如果您想具体了解新病例的数量,则为:

    dict['data'][0]['newCases'])
    

    这只是在您拥有的嵌套字典和列表链中进行操作。虽然可能有更好的方法来完成你想做的事情 tbh

    【讨论】:

      【解决方案3】:

      您的顶级字典中没有 date 键。您需要索引到data,然后从该值中选择一个字典,然后才能获得date

      >>> dx = {
      ...  'length': 601,
      ...  'maxPageLimit': 2500,
      ...  'totalRecords': 601,
      ...  'data': [{'date': '2021-12-13', 'newCases': 97},
      ...           {'date': '2021-12-12', 'newCases': 64}],
      ... }
      >>> dx.get('data')
      [{'date': '2021-12-13', 'newCases': 97}, {'date': '2021-12-12', 'newCases': 64}]
      >>> dx.get('data')[0]
      {'date': '2021-12-13', 'newCases': 97}
      >>> dx.get('data')[0].get('date')
      '2021-12-13'
      

      另外,请注意多个值共享同一个键。您在一个列表中有多个字典,每个字典都有匹配的键 - 但它们不是同一个字典!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-12
        • 2020-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-19
        • 2022-11-11
        • 1970-01-01
        相关资源
        最近更新 更多