Как выбрать случайный элемент из случайного словаря?

Итак, я делаю проект, который по сути является генератором случайных цитат для персонажей из пьесы Шекспира «Макбет». У меня возникли проблемы с созданием случайной функции, которая будет обращаться к случайному словарю, вытаскивать случайную цитату и затем печатать ее. Любая помощь приветствуется.

Вот код:

import random
Malcolm_quotes = {
    1:"'This murderous shaft that’s shot hath not yet lighted.'",
    2:"'Let every soldier hew him down a bough and bear’t before him.'",
    3:"'Cousins, I hope the days are near at hand that chambers will be safe.'",  
    4:"'Let grief convert to anger.'",
    5:"'Blunt not the heart, enrage it!'",
    6:"'Let every soldier hew him down a bough and bear’t before him.'"
}
The_3_Witches = {
    1:"'By the pricking of my thumbs, something wicked this way comes.'",
    2:"Fair is foul, and foul is fair; Hover through the fog and filthy air.",
    3:"'Here I have a pilot’s thumb, wracked as homeward he did come.'",
    4:"'Double, double toil and trouble; Fire burn and caldron bubble!'",
    5:"'All hail, Macbeth, hail to thee, thane of Cawdor. All hail, Macbeth, thou shalt be king hereafter!'",
    6:"'Macbeth shall never vanquished be until Great Birnam Wood to high Dunsinane Hill shall come against him.'"
}


Banquo_quotes = {  
    1:"'And oftentimes, to win us to our harm the instruments of darkness tell us truths, win us with honest trifles, to betray’s in deepest consequence.' ",
    2:"'What, can the devil speak true?'",
    3:"'Were such things here as we do speak about? Or have we eaten on the insane root that takes the reason prisoner?'",
    4:"'O treachery! Fly, good Fleance, fly, fly, fly! Thou may’st revenge – O slave!'",
    5:"'A heavy summons lies like lead upon me, and yet I would not sleep.'",
    6:"'Thou hast it now: king, Cawdor, Glamis, all, as the weird women promised, and, I fear, thou play’dst most foully for’t.'"}
Macduff_quotes = {
    1:"'I have no words: my voice is in my sword, thou bloodier villian than terms can give thee out.' ",
    2:"'Macduff was from his mother's womb untimely ripp'd.'",
    3:"'Bleed, bleed, poor country! Great tyranny, lay thou thy basis sure, for goodness dare not check thee.'",
    4:"'Tyrant, show thy face! If thou beest slain, and with no stroke of mine, my wife and children’s ghosts will haunt me still...'",
    5:"'I laid their daggers ready;He could not miss ‘em. Had he not resembled my father as he slept, I had done’t.'",
    6:"'O horror, horror, horror, Tongue nor heart cannot concieve nor name thee!'"
}
Lady_Macbeth_quotes = {
    1:"'Tis the eye of childhood, That fears a painted devil.' ",
    2:"'All the perfumes of Arabia will not sweeten this little hand.'",
    3:"'What's done cannot be undone.'",
    4:"'Come you spirits, That tend on mortal thoughts,unsex me here.'",
    5:"'I laid their daggers ready;He could not miss ‘em. Had he not resembled my father as he slept, I had done’t.'",
    6:"'Screw your courage to the sticking place, and we'll not fail.'"
}
Macbeth_quotes = {
     1:"'False face must hide what the false heart doth know.'",
     2:"'Blood will have blood.'",
     3:"'To prick the sides of my intent, but only vaulting ambition, which o’erleaps itself and falls on th’other'",
     4:"'I dare do all that may become a man; Who dares do more is none.'",
     5:"'Come what come may, time and the hour runs through the roughest day'",
     6:"'Nothing is but what is not.'"
}   #if x= = "random":
    #?
Почему в Python есть оператор "pass"?
Почему в Python есть оператор "pass"?
Оператор pass в Python - это простая концепция, которую могут быстро освоить даже новички без опыта программирования.
Некоторые методы, о которых вы не знали, что они существуют в Python
Некоторые методы, о которых вы не знали, что они существуют в Python
Python - самый известный и самый простой в изучении язык в наши дни. Имея широкий спектр применения в области машинного обучения, Data Science,...
Основы Python Часть I
Основы Python Часть I
Вы когда-нибудь задумывались, почему в программах на Python вы видите приведенный ниже код?
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
Алиса и Боб имеют неориентированный граф из n узлов и трех типов ребер:
Оптимизация кода с помощью тернарного оператора Python
Оптимизация кода с помощью тернарного оператора Python
И последнее, что мы хотели бы показать вам, прежде чем двигаться дальше, это
Советы по эффективной веб-разработке с помощью Python
Советы по эффективной веб-разработке с помощью Python
Как веб-разработчик, Python может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
0
0
63
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

x = random.randint(1,6) получает случайное число от 1 до 6 (включительно).

Для каждого из ваших диктов вы получаете доступ к случайному участнику, взяв x.

Обратите внимание, что это очень связано с вашими ключами, а не с общим решением.

это был точный метод, который я использовал для выбора цитаты, спасибо

Zane Ritchie 12.02.2023 20:11
Ответ принят как подходящий

Использовать:

quote_list = [Malcolm_quotes, The_3_Witches, Banquo_quotes, Macduff_quotes, Lady_Macbeth_quotes, Macbeth_quotes]

myquote = random.choice(list((random.choice(quote_list)).values()))

print(myquote)

Tysm, это сработало как шарм

Zane Ritchie 12.02.2023 20:03

Другие вопросы по теме