Home > front end >  How can I add multiple numbers to some keys in a dictionary?
How can I add multiple numbers to some keys in a dictionary?

Time:10-12

mydict = {'5': 0, '2': 0, '1': 0, '12': 0}

number = input()

for i in range(0,4):
    if number == mydict[i]:
        mydict.keys[i] =1

print(mydict)

I want input be like

  • 5 --> {'5': 1, '2': 0, '1': 0, '12': 0} or
  • 2 --> {'5': 0, '2': 1, '1': 0, '12': 0}

CodePudding user response:

What's wrong with simply not doing a loop:

mydict[number]  = 1

CodePudding user response:

Dictionaries are in hashmap group, so to find an item, there is no need for iteration over all the elements.

simply try:

mydict = {'5': 0, '2': 0, '1': 0, '12': 0}

inp = input()
mydict[inp] = mydict.get(inp, 0)   1

It also allows you to enter numbers that are not currently in the dictionary with the initial value of 0 if it is the case you are looking for. Otherwise just get the key and increment it's value:

mydict[inp]  = 1
  • Related