我想制作一个字典,记录我所看过的所有动漫和我读过的漫画。我希望按键是“ 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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句