I am trying to get my class working but I can only seem to add 2 items and I can't add the duplicate item.
I have also tried using for loops but I can't seem to get that to work either.
List of words to add:
words = Bag()
words.add('once')
words.add('twice')
words.add('twice')
My code:
class Bag:
def __init__(self):
"""Create a new empty bag."""
self.bag = dict()
def add(self, item):
"""Add one copy of item to the bag. Multiple copies are allowed."""
if not item in self.bag:
self.bag[item] = 1
else:
self.bag[item] += 1
print(self.bag)
1 Answer 1
You want results to look like {'once': 1, 'twice': 2, 'twice': 3}.
This is not possible, you can't have same key multiple times in a dict. But you can get structure like [{'once': 1}, {'twice': 2}, {'twice': 3}] with this code:
from collections import defaultdict
class Bag:
def __init__(self):
"""Create a new empty bag."""
self.index = 0
self.bag = []
def add(self, item):
"""Add one copy of item to the bag. Multiple copies are allowed."""
self.index += 1
self.bag.append({item: self.index})
answered Mar 13, 2019 at 19:27
jozo
4,8722 gold badges31 silver badges30 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Cypher
thank you for your replies, my code works to a point i cant get my code to add 'twice' twice into my dictionary only shows 2 entries and not 3 items
jozo
How should correct result looks like? Isn't
{'once': 1, 'twice': 2} correct?Cypher
the correct result should look like this {'once': 1, 'twice': 2, 'twice': 3}
jozo
I edited my answer. You can't get what you want but you can have something similar.
Cypher
Genius! thank you! I understand where I went wrong now!
lang-py
for x in self.bag.values(): print(x)