0

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)
asked Mar 13, 2019 at 19:11
4
  • But... your code is working. Commented Mar 13, 2019 at 19:19
  • 1
    Your code works perfectly for me. Do you get an error? What is your expected vs actual output? Commented Mar 13, 2019 at 19:19
  • for x in self.bag.values(): print(x) Commented Mar 13, 2019 at 19:20
  • 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 item Commented Mar 13, 2019 at 19:32

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

5 Comments

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
How should correct result looks like? Isn't {'once': 1, 'twice': 2} correct?
the correct result should look like this {'once': 1, 'twice': 2, 'twice': 3}
I edited my answer. You can't get what you want but you can have something similar.
Genius! thank you! I understand where I went wrong now!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.