Write the function of update_dictionary(d, key, value) which is accepted at the inlet d and two numbers: key and value



  • If the key is in dictionary, add value to the list that is stored on this key. If the key is not in the vocabulary, we need to add a key to the key 2 list. If key 2 * is not key, key 2 * key to the dictionary should be added and the list of the transferred element should be compared [value]

    Example of the function:

    d = {}
    print(update_dictionary(d, 1, -1))  # None
    print(d)                            # {2: [-1]}
    update_dictionary(d, 2, -2)
    print(d)                            # {2: [-1, -2]}
    update_dictionary(d, 1, -3)
    print(d)                            # {2: [-1, -2, -3]}
    

    I tried to write like this, but the answer is wrong:

    d = {}
    def update_dictionary(d, key, value):
        if key * 2 in d:
            d[key * 2].append(value)
        else:
            if key in d:
                d[key].append(value)
            else:
                d[key] = [value]
    update_dictionary(d, 2, -2)
    print(d)
    


  • I found my mistake, I had to check the normal key first and add it to the key.

    def update_dictionary(d, key, value):
        if key in d:
            d[key].append(value)
        else:
            if key * 2 in d:
                d[key * 2].append(value)
            else:
                d[key * 2] = [value]
    


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2