-1

I was looking to create a program which takes a colour name and how many kids liked it then appends it to a dictionary, however I wanted to make it so that if a duplicated key is entered it's value will be added to the existing one. Such as red 4 red 3 would print red 7. Thanks!

colourPick = True
while colourPick:
    colour = input()
    numPicked = input()
    my_dict[colour] = numPicked

3 Answers3

1

I relsolved it like this. I added a temporary way to get out of the cycle but you can modify it. This code should work. Obviously, checks on the inputs ar missing. Colours works with strings and pick with integre values

colourpick=True
dict={}
while colourpick:

 colour=input('colour ')
 pick=int(input('number '))
 if colour in dict:
     dict[colour]+=pick
 else:
     dict[colour]=pick
 inp=input('continue ')
 if inp=='.':
     break
print(dict)
Retro
  • 11
  • 3
0

To solve this problem, I only added an if else statement that checks if the colour already exists in the dict, in order to decide what to do with the numPicked variable.

colourPick = True
while colourPick:
    colour = input()
    numPicked = input()
    if colour in my_dict:  # This checks if there is already that *colour* in the dict
        my_dict[colour] += numPicked
    else:
        my_dict[colour] = numPicked
Marco
  • 111
  • 3
  • Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users with similar issues. – FluffyKitten Sep 13 '20 at 05:43
0

The simplest way, I think, would be to check whether the key exists by using if colour in my_dict:, but you can also use the method get(key, default_value) to simplify this a bit:

colourPick = True
while colourPick:
    colour = input()
    numPicked = input()
    previous = my_dict.get(colour, 0)
    my_dict[colour] = previous + numPicked

So when colour is not yet in my_dict, then previous would is 0. See also Why dict.get(key) instead of dict[key]?

Walter
  • 136
  • 3