【问题标题】:How to insert dictionary function into another dictionary function while changing key to id_number?如何在将键更改为 id_number 时将字典函数插入另一个字典函数?
【发布时间】:2019-06-05 04:14:09
【问题描述】:

问题的目标是:

  • 实例化一个名为pokedex的空字典

  • 定义一个新函数,该函数将接受 pokedex, poke_id, poke_name, poke_type 的参数

  • 使用我的字典函数create_pokemon 并在pokedex 字典中添加一个新的key:value 对,其中keypoke_idvalue 是新创建的口袋妖怪字典

我创建了一个字典函数:create_pokemon(poke_id, poke_name, poke_type)。密钥是'hp','defense', 'special_defense',名单还在继续。

这是我的create_pokemon 函数:


    new_pokemon= {

        'poke_id': poke_id,
        'poke_name': poke_name,
        'poke_type': poke_type,
        'hp': np.random.randint(400,501),
        'attack': np.random.randint(50,101),
        'defense': np.random.randint(50,101),
        'special_attack' : np.random.randint(100,151),
        'special_defense': np.random.randint(100,151),
        'speed': np.random.randint(0,101)      

    }```





so when I display pokedex, it should look something like:

```{1: {'attack': 64,
  'defense': 59,
  'hp': 495,
  'poke_id': 1,
  'poke_name': 'charmander',
  'poke_type': 'fire',
  'special_attack': 100,```

【问题讨论】:

  • 您只是想弄清楚将字典添加到另一个字典的语法吗?
  • This is my create_pokemon function: 看不到任何功能...

标签: python function dictionary key


【解决方案1】:
newPokemon = create_pokemon()
id = newPokemon['poke_id']
pokedex[id] = newPokemon

应该可以解决问题,除非我在问题描述中遗漏了某些内容

【讨论】:

  • 由于create_pokemon 的输入包含poke_id,因此不需要变量newPokemonidpokedex[poke_id] = create_pokemon(poke_id, poke_name, poke_type)
  • 是的,这是正确的,只要我们使用提供的功能。我没有看到任何存根,而且似乎混淆是围绕创建具有字典值的字典,所以我尝试稍微清除这部分。
猜你喜欢
  • 1970-01-01
  • 2019-09-24
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多