Python 当我想增加对象并让他听写时,输入错误
我想迭代整个Python 当我想增加对象并让他听写时,输入错误,python,json,loops,dictionary,key,Python,Json,Loops,Dictionary,Key,我想迭代整个数据列表,并创建具有递增值的dict,其中键将是userId。我有userId并在循环中添加了1,但我收到了一个错误:KeyError:100 todos = {} data = [ { "userId": 100, "id": 1, "title": "delectus aut autem", "completed": True }, { "userId": 200, "id": 2, "title": "qui
数据
列表,并创建具有递增值的dict,其中键将是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
字典todos为空,您正在尝试在todos中查找键为100(i['userId'])的值,但该值不存在。您需要先将条目添加到字典中,然后再尝试将条目添加到字典中。如果“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
两件事:
将返回第一个dict的值,即i['userId']
100
是一个空的dict,所以里面没有任何键李>todos
userId
?)的和),我认为你想在这里求userId
的和
如果您不确定字典中的内容(但仍然知道其值将是整数),我建议您使用defaultdict
:
要改进@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
使用集合。计数器
print(Counter(x['userId'] for x in data))
# Counter({100: 1, 200: 1, 300: 1})
print(Counter(x['userId'] for x in data))
# Counter({100: 1, 200: 1, 300: 1})