How to use dictionary words inside a variable with random? Error: return seq [i] KeyError: 1

Question:

This executable code works fine. In the variable subject there is ["della gara", "del match"] which are executed with the function random, so subject = ["della gara", "del match"]

Considering that ["della gara", "del match"] are the same as the nouns dictionary, I would like to directly use nouns as the subject variable. Precisely I would like to use subject = nouns, because I would have to add so many other words in the nouns dictionary and I would not want to repeat them again in subject = ["della gara", "del match", etc. etc. etc ….].

Writing subject = nouns I get the error:

     random_subject = random.choice (subject)
   File "/usr/lib/python3.8/random.py", line 291, in choice
     return seq [i]
KeyError: 1

How can I use nouns dictionary words in subject?

from tkinter import ttk
import tkinter as tk
from tkinter import *

root = tk.Tk()
root.geometry("400x150")

#from diz_test2 import nouns
#from diz_test2 import article_words

import random

text = tk.Text(root,width=43,height=2)
text.place(x=15, y=50)


nouns = {

        "della gara": {"genere" : "femminile", "unità" : "singolare", "apostrofo" : "no"},
        "del match": {"genere" : "maschile", "unità" : "singolare", "apostrofo" : "no"},
        }

article_words = {
    
            "valido" : {
            "genere" : "maschile",
            "unità" : "singolare",
            "apostrofo" : "no"
            },        

            "valida" : {
            "genere" : "femminile",
            "unità" : "singolare",
            "apostrofo" : "no"
            },                
        }


####################
subject = ["della gara", "del match"]
#subject = nouns





def getArticle(random_subject):  

    for key, value in article_words.items():
        if nouns[random_subject] == value:
            return key

def printTeam():
    random_subject = random.choice(subject)
    article = getArticle(random_subject)

    def articolo1():
        phrase = f"{random_subject} {article}"
        text.insert(tk.END, phrase)

    articolo1()

button2 = Button(root, text="Print", command = printTeam)
button2.pack()
button2.place(x=15, y=100)

root.mainloop()
Asked By: Jas_99

||

Answers:

In order to get the keys of the dictionary as a list, you can try any of these:

subject = list(nouns.keys())

subject = [*nouns]

subject = [key for key in nouns.keys()]

Answered By: Ignatius Reilly