用Python制作字典

时间:2018-08-20 16:52:24

标签: python dictionary

我试图用鲍勃的名言来制作字典,但一直被告知我使用的是“无效语法”。我究竟做错了什么?我正在尝试从字典中拉出随机键并显示引号...

bob_sayings = { 1: "I wish I was where I was when I wished I was here", 
   2:"There's a fine line between fishing and standing on the shore like an idiot.", 
   3: "After accomplishing a goal just look around to see whether you lost something or someone"}

bob_sayings

bob_sayings[randint(1, 3)

5 个答案:

答案 0 :(得分:2)

您的无效语法来自最后一行,您没有在其中括住括号。另外,在第二行中,您有一个不执行任何操作的变量。

无论如何,重要的是:字典应该具有有意义的键。就您而言,这更像是伪装成字典的列表。更好的方法是写类似

的东西
from random import choice
sayings = ['something', 'something else', 'another thing']
print(choice(sayings))

答案 1 :(得分:2)

要回答第一个问题,您会遇到语法错误,因为您缺少代码末尾的右方括号。

就像其他人提到的那样,当键是连续整数时,您不需要使用字典。相反,您可以尝试使用列表或元组。然后,您可以改用random.choice,这样就不必弄乱索引了。这样做的主要好处是您可以向序列中添加项目,而无需在其他地方更改代码。这是一个例子。

import random

bob_sayings = ( 
    "I wish I was where I was when I wished I was here", 
    "There's a fine line between fishing and standing on the shore like an idiot.", 
    "After accomplishing a goal just look around to see whether you lost something or someone"
)

bob_says = random.choice(bob_sayings)
print(bob_says)

答案 2 :(得分:1)

from random import randint
bob_sayings = { 1: "I wish I was where I was when I wished I was here", 2:"There's a fine line between fishing and standing on the shore like an idiot.", 3: "After accomplishing a goal just look around to see whether you lost something or someone"}
bob_sayings[randint(1, 3)]

您最后缺少]

答案 3 :(得分:1)

您需要添加

from random import randint

在第一行。另外,您还需要在最后一行的末尾添加]

from random import randint

bob_sayings = { 1: "I wish I was where I was when I wished I was here",
   2:"There's a fine line between fishing and standing on the shore like an idiot.",
   3: "After accomplishing a goal just look around to see whether you lost something 
   or someone"}

bob_sayings

bob_sayings[randint(1, 3)]

答案 4 :(得分:0)

可能您忘记了bob_sayings [random.randint(1,3)]末尾的括号

restype