列表映射Python

时间:2018-04-16 13:50:51

标签: python

我正在寻找关于python的指导/助手。我不是专家,这是我的第一次。

问题是:

给定参数名称列表和数值列表,创建一个将名称映射到值的字典。

{
  "data": {
    "google": {
      "expectUserResponse": true,
      "richResponse": {
        "items": [
          {
            "simpleResponse": {
              "textToSpeech": "Choose an item"
            }
          }
        ]
      },
      "systemIntent": {
        "intent": "actions.intent.OPTION",
        "data": {
          "@type": "type.googleapis.com/google.actions.v2.OptionValueSpec",
          "listSelect": {
            "title": "Hello",
            "items": [
              {
                "optionInfo": {
                  "key": "first title"
                },
                "description": "first description",
                "image": {
                  "url": "https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png",
                  "accessibilityText": "first alt"
                },
                "title": "first title"
              },
              {
                "optionInfo": {
                  "key": "second"
                },
                "description": "second description",
                "image": {
                  "url": "https://lh3.googleusercontent.com/Nu3a6F80WfixUqf_ec_vgXy_c0-0r4VLJRXjVFF_X_CIilEu8B9fT35qyTEj_PEsKw",
                  "accessibilityText": "second alt"
                },
                "title": "second title"
              }
            ]
          }
        }
      }
    }
  }
}

这是样本值之后应显示的格式。

我能够构建这个,但它将单引号放在数值上

def get_params(sparams):
    r"""
    Input: sparams : str
    Output: params : dict
    >>> get_params("atoms = 100")
    {'atoms': 100.0}
    >>> get_params("dt = 0.001\n" \
    ...           +"temp = 300\n")
    {'dt': 0.001, 'temp': 300.0}
    >>> get_params("press = 10\n" \
    ...           +"vol   = 220\n")
    {'press': 10.0, 'vol': 220.0}
    >>> get_params("dt = 0.002\n" \
    ...           +"N  = 3000\n" \
    ...           +"temp  = 320\n" \
    ...           +"press = 1\n" \
    ...           +"L     = 20\n")
    {'press': 1.0, 'dt': 0.002, 'L': 20.0, 'temp': 320.0, 'N': 3000.0}
    """
$#return {'dt': 0.001, 'N': 400.0}

1 个答案:

答案 0 :(得分:1)

您已经非常接近了,但是您将值v保存为字符串。您需要将其转换为数值。如果您将最后一行编辑为mydict[k] = float(v),那么我认为它应该有效。