访问键内的索引/值(Python)

时间:2015-08-18 17:41:43

标签: python dictionary key indexof

我有一个包含18个不同键的字典,每个键都有3个值(xPowerxPPxAccuracy)每个变量都包含一个int。我如何从某个键访问一个值?例如,我想取出ScratchPower(40)的值以供其他地方使用。搜索了半个多小时后,我发现的最多的是访问密钥中的所有值:

print defMoves["Scratch"]

这是我的字典:

defMoves = {
    "Scratch": [ScratchPower, ScratchPP, ScratchAccuracy],
    "Air Slash": [Air_SlashPower, Air_SlashPP, Air_SlashAccuracy],
    "Flare Blitz": [Flare_BlitzPower, Flare_BlitzPP, Flare_BlitzAccuracy],
    "Growl": [GrowlPower, GrowlPP, GrowlAccuracy],
    "Heat Wave": [Heat_WavePower, Heat_WavePP, Heat_WaveAccuracy],
    "Ember": [EmberPower, EmberPP, EmberAccuracy],
    "Shadow Claw": [Shadow_ClawPower, Shadow_ClawPP, Shadow_ClawAccuracy],
    "Smokescreen": [SmokescreenPower, SmokescreenPP, SmokescreenAccuracy],
    "Dragon Claw": [Dragon_ClawPower, Dragon_ClawPP, Dragon_ClawAccuracy],
    "Dragon Rage": [Dragon_RagePower, Dragon_RagePP, Dragon_RageAccuracy],
    "Scary Face": [Scary_FacePower, Scary_FacePP, Scary_FaceAccuracy],
    "Fire Fang": [Fire_FangPower, Fire_FangPP, Fire_FangAccuracy],
    "Flame Burst": [Flame_BurstPower, Flame_BurstPP, Flame_BurstAccuracy],
    "Wing Attack": [Wing_AttackPower, Wing_AttackPP, Wing_AttackAccuracy],
    "Slash": [SlashPower, SlashPP, SlashAccuracy],
    "Flamethrower": [FlamethrowerPower, FlamethrowerPP, FlamethrowerAccuracy],
    "Fire Spin": [Fire_SpinPower, Fire_SpinPP, Fire_SpinAccuracy],
    "Inferno": [InfernoPower, InfernoPP, InfernoAccuracy],
}

由于

2 个答案:

答案 0 :(得分:1)

defMoves["Scratch"]返回一个列表,所以只需索引就像任何列表一样:

defMoves["Scratch"][0]  # first subelement -> ScratchPower
defMoves["Scratch"][1]  # second subelement -> ScratchPP
defMoves["Scratch"][2]  # third subelement -> ScratchAccuracy
......

答案 1 :(得分:0)

defMoves [“Scratch”]让你回到这个值,在这种情况下是一个列表,与该键相关联。要从该列表中获取特定项,您需要使用数字索引。因此,例如,要获得ScratchPower,您将使用defMoves [“Scratch”] [0]。

但是,这似乎很难跟踪,所以你可能想在每个词典中使用另一个词典。那看起来像是

{"Scratch" : {"Power":40... }... }