kiice5 kiice5 - 1 year ago 102
Python Question

Tkinter ListBox and dictionaries

Displaying list items in a tkinter listbox looks like this:

from tkinter import *

root = Tk()

lst = ["one", "two", "three"]
lstbox = Listbox(root)

for item in lst:
lstbox.insert(END, item)


How can I display a dictionary with both its keys and values using a listbox?

Answer Source

Iterate over the keys of the dictionary and insert a string comprising the key and its value. You can use str.format() to create the string. Here's an example:

d = {"one": 1, "two": 2, "three": 3}

for key in d:
    lstbox.insert(END, '{}: {}'.format(key, d[key]))

Note that the items will not be in any particular order because dictionaries are unordered. You could sort the keys like this:

for key in sorted(d):
    lstbox.insert(END, '{}: {}'.format(key, d[key]))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download