Reputation: 516
I want to make a dictionary keeping track of all anime I've seen and manga I've read. I want the keys to be "Anime" and "Manga" and their values to be lists in which I can add the series I've seen.
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)
The values are not in lists but are added just as they are. I've linked the output.
I want the output to be
{'Anime' : [Monster, Legend of the Galactic Heroes],
'Manga' : [Berserk, 20th Century Boys] }
Upvotes: 2
Views: 80
Reputation: 16633
You are almost there. Try these modifications. It uses defaultdict
, which can make your code more concise:
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))
Output:
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']}
Also, you can run the same code again in the future, and it will simply add entries to amanga
.
Upvotes: 4
Reputation: 9529
You could change your original code to be something like this, this is not the most elegant way but it is good starting point to figure out what was the problem:
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)
Output:
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']}
You already know that you have only 2 types of types (Anime and Manga) so you can create dict with these two keys and then append entries to them.
Upvotes: 1