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

时间:2019-01-14 07:09:25

标签: 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] }

2 个答案:

答案 0 :(得分:4)

您快到了。尝试这些修改。它使用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添加条目。

答案 1 :(得分:1)

您可以将原始代码更改为这样,这不是最优雅的方法,但是它是找出问题所在的好起点:

amanga = {'Anime':[], 'Manga':[]}
#total = 0

for x in range (2):
    x = input("Anime or Manga? ") #some data validation would be handy here to ensure right key is choosen
    print("How many entries? ")
    n = int(input())
    for i in range (n):
        amanga[x].append(input("Entry: "))

print (amanga)

输出:

Anime or Manga? 'Anime'
How many entries? 
2
Entry: 'a'
Entry: 'b'
Anime or Manga? 'Manga'
How many entries? 
1
Entry: 'n'
{'Anime': ['a', 'b'], 'Manga': ['n']}

您已经知道只有两种类型的类型(动漫和漫画),因此可以使用这两个键创建字典,然后将条目追加到它们。