我想制作一本字典来记录我看过的所有动漫和漫画。我希望键是“Anime”和“Manga”,它们的值是列表,我可以在其中添加我看过的系列。
amanga = {}
#total = 0
for x in range (2):
x = input("Anime or Manga? ")
print("How many entries? ")
n = int(input())
for i in range (n):
amanga[x[i]] = input("Entry: ")
print (amanga)
这些值不在列表中,但会按原样添加。我已经链接了输出。
我想要的输出是
{'Anime' : [Monster, Legend of the Galactic Heroes],
'Manga' : [Berserk, 20th Century Boys] }
最佳答案
你就快到了。尝试这些修改。它使用defaultdict
,这可以让你的代码更加简洁:
from collections import defaultdict
# Create a dictionary, with the default value being `[]` (an empty list)
amanga = defaultdict(list)
for _ in range(2):
media_type = input("Anime or Manga? ")
n = int(input("How many entries?\n"))
amanga[media_type].extend([input("Entry: ") for _ in range(n)])
print(dict(amanga))
输出:
Anime or Manga? Anime
How many entries?
2
Entry: Monster
Entry: Legend of the Galacic Heroes
Anime or Manga? Manga
How many entries?
2
Entry: Berserk
Entry: 20th Century Boys
{'Anime': ['Monster', 'Legend of the Galacic Heroes'], 'Manga': ['Berserk', '20th Century Boys']}
此外,您可以在将来再次运行相同的代码,它只会向 amanga
添加条目。
关于python - 如何将列表作为值合并到字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54177047/