检索词典值Python

时间:2013-12-20 07:41:44

标签: python dictionary

我目前有一个包含相当大字典的程序。

cards = {1.1:"Ace of Spades",
     1.2:"Ace of Clubs", 
     1.3:"Ace of Diamonds", 
     1.4:"Ace of Hearts", 

     2.1:"Two of Spades", 
     2.2:"Two of Clubs", 
     2.3:"Two of Diamonds",
     2.4:"Two of Hearts",

     3.1:"Three of Spades",
     3.2:"Three of Clubs",
     3.3:"Three of Diamonds",
     3.4:"Three of Hearts",

     4.1:"Four of Spades",
     4.2:"Four of Clubs",
     4.3:"Four of Diamonds",
     4.4:"Four of Hearts",

     5.1:"Five of Spades",
     5.2:"Five of Clubs",
     5.3:"Five of Diamonds",
     5.4:"Five of Hearts",

     6.1:"Six of Spades",
     6.2:"Six of Clubs",
     6.3:"Six of Diamonds",
     6.4:"Six of Hearts",

     7.1:"Seven of Spades",
     7.2:"Seven of Clubs",
     7.3:"Seven of Diamonds",
     7.4:"Seven of Hearts",

     8.1:"Eight of Spades",
     8.2:"Eight of Clubs",
     8.3:"Eight of Diamonds",
     8.4:"Eight of Hearts",

     9.1:"Nine of Spades",
     9.2:"Nine of Clubs",
     9.3:"Nine of Diamonds",
     9.4:"Nine of Hearts",

     10.1:"Ten of Spades",
     10.2:"Ten of Clubs",
     10.3:"Ten of Diamonds",
     10.4:"Ten of Hearts",

     11.1:"Jack of Spades",
     11.2:"Jack of Clubs",
     11.3:"Jack of Diamonds",
     11.4:"Jack of Hearts",

     12.1:"Queen of Spades",
     12.2:"Queen of Clubs",
     12.3:"Queen of Diamonds",
     12.4:"Queen of Diamonds",

     13.1:"King of Spades",
     13.2:"King of Clubs",
     13.3:"King of Diamonds",
     13.4:"King of Hearts"}

我希望能做什么。例如,打印出11.2(Jack of Clubs)的相应值。然后我还要打印出Jack of Clubs(11.2)的相应值。

我该怎么做?

编辑

此外,我想补充一点,每次都不会是相同的值。它会被改变。程序生成1到13之间的随机数,然后在1到4之间生成另一​​个随后的数字,然后将这两个附加到#。#然后我想要检索该浮点数的相应值。

1 个答案:

答案 0 :(得分:1)

打印出随机选择的数字的相应值将很容易:

print cards[randomNumber]

当您想要进行反向查找并打印出与“Jack of Clubs”相对应的值或任何相应的卡名称时,会出现问题。使用传统字典,这将花费很长时间,因为它将涉及搜索字典中的每个值。

为避免这种情况,您只需创建两个词典即可。但是,使用David Zwicker链接到的Two way/reverse map问题中的一个建议会更有效。