【问题标题】:KeyError when I want to increase object and put him to dict当我想增加对象并将他放入 dict 时出现 KeyError
【发布时间】:2018-12-06 04:01:13
【问题描述】:

我想遍历整个data 列表并创建具有增加值的字典,其中键为userId。我有 userId 并在循环中添加了 1,但我收到了一个错误:KeyError: 100

todos = {}

data = [
  {
    "userId": 100,
    "id": 1,
    "title": "delectus aut autem",
    "completed": True
  },
  {
    "userId": 200,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": True
  },
  {
    "userId": 300,
    "id": 3,
    "title": "fugiat veniam minus",
    "completed": True
  }
]

for i in data:
  todos[i['userId']] += 1 

【问题讨论】:

    标签: python json loops dictionary key


    【解决方案1】:

    字典 todos 为空,您试图在 todos 中查找键为 100 (i['userId']) 的值,但它不存在。在尝试添加条目之前,您需要先将条目添加到字典中。

    【讨论】:

      【解决方案2】:

      如果“todos”字典中不存在该元素,您会错过插入该元素,我将您的代码更改为:

      todos = {}    
      data = [
        {
          "userId": 100,
          "id": 1,
          "title": "delectus aut autem",
          "completed": True
        },
        {
          "userId": 200,
          "id": 2,
          "title": "quis ut nam facilis et officia qui",
          "completed": True
        },
        {
          "userId": 300,
          "id": 3,
          "title": "fugiat veniam minus",
          "completed": True
        }
      ]
      
      for i in data:
        if i['userid'] in todos: # if key data exist in the dict, it update the value
            todos[i['userId']] += 1 
        else
           todos[i['userid']]=1 ## otherweise it create a new item with value set to 1
      

      【讨论】:

        【解决方案3】:

        两件事:

        • i['userId'] 将返回值,即您的第一个字典的 100
        • todos 是一个空字典,所以你不会有任何密钥。

        我不确定你想做什么(计算字典的数量?求和userId?),我认为你想在这里得到userId 的总和。

        如果您不确定字典中的内容(但仍知道其值将是整数),我建议您使用 defaultdict

        from collections import defaultdict
        
        todos = defaultdict(int)
        
        data = [
          {
            "userId": 100,
            "id": 1,
            "title": "delectus aut autem",
            "completed": True
          },
          {
            "userId": 200,
            "id": 2,
            "title": "quis ut nam facilis et officia qui",
            "completed": True
          },
          {
            "userId": 300,
            "id": 3,
            "title": "fugiat veniam minus",
            "completed": True
          }
        ]
        
        for i in data:
          todos['userId'] += i['userId']
        

        【讨论】:

          【解决方案4】:

          改进@jc1850 的答案: 为了解决这个问题,您可以更改代码以检查密钥是否存在:

          for i in data
              userid = i['userId']
              if userid not in todos: todos[userid] = 0
              todos[i['userId']] += 1
          

          您也可以使用collections.defaultdict。对于 int 类型,如果键不存在,则假定值为 0:

          from collections import defaultdict
          
          todos = defaultdict(int)
          for i in data
              todos[i['userId']] += 1
          

          【讨论】:

            【解决方案5】:

            使用collections.Counter

            print(Counter(x['userId'] for x in data))
            # Counter({100: 1, 200: 1, 300: 1})
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2010-12-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-09-28
              相关资源
              最近更新 更多