-1

Is there a way to do this?

ex:

I have a dict

sounds = {
        'sound1.mp3': 0,
        'sound2.mp3': 0,
        'sound3.mp3': 0
    }

when a keys value (sound1 in this ex) gets updated, the command prompt will go from

sound1.mp3: 0
sound2.mp3: 0
sound3.mp3: 0

to

sound1.mp3: 1
sound2.mp3: 0
sound3.mp3: 0
hwhat
  • 326
  • 1
  • 5
  • 14
  • Print out the dictionary's items then you are done, how do you show the command prompt? please show some code.. – DDGG Mar 01 '18 at 02:12
  • @DDGG I want it updated on the same line, not constantly printed...That's what I'm asking. – hwhat Mar 01 '18 at 02:17
  • It can not be updated on the same line you print it. You should do update and the print respectively. – DDGG Mar 01 '18 at 02:24
  • Probability I know what you want, you maybe needs to use a class to hold this dictionary, and make an update method, in that method you do update first, then do print. – DDGG Mar 01 '18 at 02:27
  • @DDGG ya i didn't mean update and print on the same line. like ill have a function to update it and then print the updated dict. but idk how to have it replace the first print – hwhat Mar 01 '18 at 02:37

2 Answers2

0

This is a simple demo about what I said:

class Holder(object):
    def __init__(self, init_dict):
        self.dict = init_dict

    def increase(self, key):
        if key in self.dict:
            d = {key: self.dict[key] + 1}
            self.update(d)

    def update(self, d):
        self.dict.update(d)
        self.print_prompt()

    def print_prompt(self):
        for key in sorted(self.dict.keys()):
            print '%s: %d' % (key, self.dict[key])
        print


def main():
    sounds = {
        'sound1.mp3': 0,
        'sound2.mp3': 0,
        'sound3.mp3': 0
    }

    holder = Holder(sounds)
    holder.print_prompt()
    holder.increase('sound1.mp3')

    holder.update({
        'sound1.mp3': 3,
        'sound2.mp3': 2,
        'sound3.mp3': 1
    })


if __name__ == '__main__':
    main()

The output is:

sound1.mp3: 0
sound2.mp3: 0
sound3.mp3: 0

sound1.mp3: 1
sound2.mp3: 0
sound3.mp3: 0

sound1.mp3: 3
sound2.mp3: 2
sound3.mp3: 1
DDGG
  • 1,171
  • 8
  • 22
0

If you're working on the terminal, you can use the \r character (carriage return) to return the output to the start of the line.

For example, we can do

for i in range(10):
    time.sleep(1)
    print(i, end="\r")

Note that the prompt (in IDLE) will then overwrite the last iteration with >>>. This is because on a command prompt it literally moves the next character pointer to the beginning of the line.

If you want to avoid this, simply print a blank line afterwards.

As far as I know, the only way to re-print previous lines is to clear the screen. See This question or This question for how to clear the entire screen.

Snakes and Coffee
  • 8,747
  • 4
  • 40
  • 60