python - 如何将列表作为值合并到字典中?

标签 python list dictionary

我想制作一本字典来记录我看过的所有动漫和漫画。我希望键是“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)

这些值不在列表中,但会按原样添加。我已经链接了输出。

https://ibb.co/7b3MqBm

我想要的输出是

{'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/

相关文章:

Python 3-Tkinter destroy() 不适用于动态检查按钮

python - 在python中读取单行文件不会跳过一些空格

python - 为列表中的不同数字切换列表中的字符

python - Pandas DataFrame 中的字典嵌套列表

c# - 计算通用列表中存在的字典中值的总和

dictionary - 使用 golang 的字符串路径变量导航到 map

python - 如何在 Python 中打开 Excel 文件?

python - 这是什么时间格式? 20151104101700-0800

ios - 在 Swift 2.0 中在运行时构建字典

ios - 在单例类中追加数组并在另一个 Controller 中计数返回 0