简体   繁体   中英

Printing dictionary where the keys are static, and values dynamic in terminal

I have a REST URL It returns a large JSON object as a dictionary.

{"id": 1, "name" : bobert, "cash" : 100}

I'm doing the basic print key, value, however here's the challenge:

I need it to look like this.

id : 1 name : bobert cash : 100

^^^ I need the keys "(id, name, cash) to persist on the screen, and only the values (1, bobert, 100) to update with each new request.

This is similar to the problem of updating a single line like a progress bar, but for multiple lines.

for keys, values in my_resp.items():
  print ('  {}  =  {}  '.format(keys, values))

That code is the basic idea, but I need the keys to persist, and values to be updated.

I've looked at curses (which I think is too complicated for this) And also looked the sys.stdout.write but that only appears to work for 1 line at a time.

This is basically what I use:

def printline(line):
    sys.stdout.write(line + "\x1b[K\r")
    sys.stdout.flush()

Call as printline(string) . Use a regular print statement to move to a new line. Otherwise, successive printline calls will overwrite the same line repeatedly, as you want. This works on UNIX-like terminals: the \\x1b[K bit is an ANSI escape code which deletes to the end of the line, and the \\r moves back to the start of the line (so the next printline will overwrite the current line).

Just add a newline:

for keys, values in my_resp.items():
  print ('  {}  =  {}  '.format(keys, values))
print "\n"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM