gpt4 book ai didi

python - 如何更改字典的键和值

转载 作者:行者123 更新时间:2023-12-02 18:36:17 26 4
gpt4 key购买 nike

所以我有以下代码,我想要做的是获取输入元组的每隔一个值,并将其保存到字典中作为 dict.keydict.value 首先设置为 0。之后,我想查看保存的字典,并且每次 dict.key 出现在元组中时,我都想输入计数它位于 dict.value 中。该代码当前给我一个错误。

def movie_awards(results):
"""
I want to ignore every first value of the tuple
"""
results = list(results)

answer = {x[1]:0 for x in results}

for x in results:
answer[x[1]] = answer[x] + 1

print(answer)

result = {("Best Picture", "Parasite"),\
("Best Actor", "Joker"),\
("Best Actress", "Judy"),\
("Best Sound Editing", "Ford v Ferrari"),\
("Best Sound Editing", "1917"),\
("Best Original Score", "Joker"),\
("Best Costume Design", "Little Women"),\
("Best Visual Effects", "Little Women"),\
("Best Director", "Parasite")}

最佳答案

只需使用 += 添加数字即可:

for x in results:
answer[x[1]] += 1

print(answer)

正在做:

answer[x]

python 正在尝试获取键为 ('Best Original Score', 'Joker')key:value 对。因为它不存在,所以会引发一个关键错误。

关于python - 如何更改字典的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68712648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com