Python Forum
Access individual items of a dictionary by clicking a button
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Access individual items of a dictionary by clicking a button
#1
Hi all, I'm creating a game for my son and I'm trying to display items in a dictionary one by one when he clicks a button on the GUI.
Currently, I'm only able to display ALL items in the dictionary when the button is clicked OR just the first item. Can you help me figure out how I can display/return an item from the dictionary (key: value) with each click of the button until all items are displayed in the GUI .... I've tried for the last few days but can't figure it out.... please help! Thanks in advance.
Reply
#2
How are you getting the first item now?

Unfortunately, it's not simple to randomly select from a dictionary. The random selection methods require that you feed them a sequence, which a dictionary is not. So you end up having to massage it into a list and pick the item from that. Unless you had a massive dictionary, I'd do this to keep the code short.


import random

d = {"a": "apple", "b": "banana", "c": "cherry", "d": "date"}
key, value = random.choice(list(d.items()))
print(key, value)
Output:
d date
Output:
b banana
Reply
#3
Why bother with a dictionary?

from random import choice

a = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Hedgehog"]
for i in range(10):
    print(f'The word is: {choice(a)}')
If you really want a dictionary:

from random import choice

d = {"a": "apple", "b": "banana", "c": "cherry", "d": "date", }
keys = list(d.keys())
for i in range(10):
    key = choice(keys)
    print(key, d[key])
Here a quick and nasty tkinter example, run myApp() in your IDE:

import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
from random import choice

def myApp():
    d = {"a": "apple", "b": "banana", "c": "cherry", "d": "date", }
    keys = list(d.keys())
    win= tk.Tk(className="words game")
    win.geometry("700x350")
    win['background'] = 'lightblue'
    #  a function to show the popup message
    def show_msg():
        key = choice(keys)
        messagebox.showinfo('Key and Word', f'key is {key}, word is {d[key]}')
    
    tk.Label(win, text= "Wanna play a game?", font= ('Aerial 17 bold italic')).pack(pady= 30)

    # a Button to display the message
    ttk.Button(win, text= "Click Here", command=show_msg).pack(pady= 20)
    win.mainloop()
Reply
#4
(Feb-11-2026, 09:58 PM)bowlofred Wrote: How are you getting the first item now?

Unfortunately, it's not simple to randomly select from a dictionary. The random selection methods require that you feed them a sequence, which a dictionary is not. So you end up having to massage it into a list and pick the item from that. Unless you had a massive dictionary, I'd do this to keep the code short.


import random

d = {"a": "apple", "b": "banana", "c": "cherry", "d": "date"}
key, value = random.choice(list(d.items()))
print(key, value)
Output:
d date
Output:
b banana

Currently I'm next(iter()) functions and to display all items I use the while loop which returns everything.....I tried the random function also but because the keys show the order in which they should appear (e.g. "Clue 1, Clue 2....") also some items are repeated which is not ideal Cry
Reply
#5
(Feb-12-2026, 04:11 PM)AdeS Wrote:
(Feb-11-2026, 09:58 PM)bowlofred Wrote: How are you getting the first item now?

Unfortunately, it's not simple to randomly select from a dictionary. The random selection methods require that you feed them a sequence, which a dictionary is not. So you end up having to massage it into a list and pick the item from that. Unless you had a massive dictionary, I'd do this to keep the code short.


import random

d = {"a": "apple", "b": "banana", "c": "cherry", "d": "date"}
key, value = random.choice(list(d.items()))
print(key, value)
Oh by the way, I don't want to randomly return the items of the dictionary, my intention is to return them in the order they exist in the dictionary.
Output:
d date
Output:
b banana

Currently I'm using the next(iter()) functions to display the first key-value pair and for all items I use the while loop which returns everything.....I tried the random function also but because the keys show the order in which they should appear (e.g. "Clue 1, Clue 2....") also some items are repeated which is not ideal Cry
Reply
#6
Aha! You don't want random choices, you want sequential choices! You might have mentioned that clearly!

Something like this?

import tkinter as tk
from tkinter import messagebox
from tkinter import ttk

def myApp():
    d = {"a": "apple", "b": "banana", "c": "cherry", "d": "date", }
    keys = list(d.keys())
    def show_msg():
        for key in keys:
            if key == keys[-1]:
                messagebox.showinfo('Last Clue', 'Last clue coming up next')        
                messagebox.showinfo('Key and Word', f'key is {key}, word is {d[key]}')
            else:
                messagebox.showinfo('Key and Word', f'key is {key}, word is {d[key]}')
    win= tk.Tk(className="words game")
    win.geometry("700x350")
    win['background'] = 'lightblue'
    tk.Label(win, text= "Wanna play a game?", font= ('Aerial 17 bold italic'), bg='green', borderwidth=3, relief="sunken").pack(ipadx = 5, ipady=5, pady= 30)
    ttk.Button(win, text= "Click Here", command=show_msg).pack(pady= 20)
    win.mainloop()
Maybe this will help. I thnk the idea maybe came from bowlofred in another thread here. It's a way of making an endless generator!

# endlessly loop through the list one at a time
def clue_giver():
    while True:
        for clue in clues:
            yield clue
Reply
#7
Hello,

It looks like you're trying to access individual items of a dictionary by clicking a button in a Tkinter GUI. You can achieve this by using the Button widget in combination with a callback function that accesses the dictionary's items.

Here's an example demonstrating how you can access dictionary items with a button click:

import tkinter as tk

# Sample dictionary
data = {
    'item1': 'Value 1',
    'item2': 'Value 2',
    'item3': 'Value 3'
}

def display_value(key):
    # This function will be called when the button is clicked
    value = data.get(key, "Key not found")
    result_label.config(text=f"{key}: {value}")

root = tk.Tk()
root.title("Dictionary Access Example")

# Create buttons for each dictionary item
for key in data:
    button = tk.Button(root, text=f"Get {key}", command=lambda key=key: display_value(key))
    button.pack()

# Label to display the result
result_label = tk.Label(root, text="Select an item")
result_label.pack()
root.mainloop()

Explanation:

Dictionary (data): This holds the key-value pairs you want to access.

Button: Each button is created for a specific dictionary key. The lambda function is used to pass the key to the display_value function when clicked.

display_value function: This function retrieves the value associated with the clicked key and updates a label with the result.

This way, when you click a button, it displays the corresponding value from the dictionary.

Let me know if you need further clarification or if something isn’t working as expected!
Hi there! I’m a Python enthusiast passionate about building projects and solving coding challenges. Currently, I’m exploring ways to integrate Python with new tools and platforms. One of the interesting tools I've come across recently is the link removed, which helps with streamlined media browsing and management. If anyone has experience using it with Python, feel free to share your insights!
Reply
#8
Create a list --> the_list = the_dict.keys(). Every time the button is clicked display the_list[0], or the_dict[the_list[0]], and then delete the_list[0]. Of course you will have to check for an empty list --> if the_list:
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question [SOLVED] Access keys and values from nested dictionary? Winfried 4 913 Nov-17-2025, 11:47 AM
Last Post: Winfried
  sharepoint: Access has been blocked by Conditional Access policies CAD79 0 3,878 Jul-12-2024, 09:36 AM
Last Post: CAD79
  How to expand and collapse individual parts of the code in Atom Lora 2 2,640 Oct-06-2022, 07:32 AM
Last Post: Lora
  how to assign items from a list to a dictionary CompleteNewb 3 3,598 Mar-19-2022, 01:25 AM
Last Post: deanhystad
Sad Selenium: can't open a new window after clicking a button and I don't know why noahverner1995 0 3,192 Jan-22-2022, 09:55 AM
Last Post: noahverner1995
  simple f-string expressions to access a dictionary Skaperen 0 2,384 Jul-15-2020, 05:04 AM
Last Post: Skaperen
  read individual nodes from an xml url using pandas mattkaplan27 5 5,403 Jul-05-2020, 10:06 PM
Last Post: snippsat
  access dictionary with keys from another and write values to list redminote4dd 6 5,957 Jun-03-2020, 05:20 PM
Last Post: DeaD_EyE
  Access list items in Python kamaleon 2 3,668 Dec-31-2019, 11:10 AM
Last Post: kamaleon
  Calculating frequency of items in a dictionary markellefultz20 1 2,757 Nov-27-2019, 04:21 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020