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

激肽

我想制作一个字典,记录我所看过的所有动漫和我读过的漫画。我希望按键是“ 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] }
iz_

你快到了。尝试这些修改。它使用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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

java stream如何将相同的值合并到列表

如何将两个数组合并到字典中?

将字典合并到列表字典中

如何将列表中的元素合并到新的嵌套列表中?

如何将多个字典的列表合并到列表字典中?

将列值合并到列表中

如何将数据帧的每一行合并到python中的列表中

如何将列表的两个列表合并到python中的pandas DataFrame中?

如何将包含字典的Python列表合并到一个最终列表中

如何将多个json / python字典合并到1个数据框中

如何将2个单独的数组合并到Excel中的广泛合并列表

如何将存储在模型中的名称和值收集到字典中,最后将这些单独的变量合并到c#mvc中

Python-如何以完全随机的顺序将两个列表合并到字典中

如何将字典列表合并到字典key:list配对中?

如何将timeDate列表合并到单个timeDate中?

如何将字典条目的值合并到字符串列表

将 2 个不同的列表合并到字典中

如何将具有相同键的字典的值从字典列表中合并为一个值?

如何将列表映射到字典键作为值

如何将两个列表统一合并到字典中

如何将 2 个字典合并到一个数组中?

如何将值列表合并到哈希图中的相同键?

将两个列表合并到字典中

将列表合并到字典列表中

如何将 Pandas DataFrame 中的数据与多索引合并到一个列表中

如何将(动态)列表数量合并到元组列表中

如何将两个单独的列表合并到对象列表中

如何使用 jq 将字典列表合并到一个字典中

如何将多个字典列表合并到一个多字典列表中?熊猫