PyDer
PyDer

Reputation: 532

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?

Upvotes: 0

Views: 4610

Answers (1)

mhawke
mhawke

Reputation: 87064

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

Upvotes: 2

Related Questions