kiice5 kiice5 - 3 months ago 31
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)
lstbox.pack()

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

root.mainloop()


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

Answer

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]))