开发者

python dictionary keys

I'm having a bit of a problem, don't even know if this is doable. I have a number of launchers that each have a interface defined with the expected inputs. The input values come as a dictionary. For example:

开发者_StackOverflow    dict_key = str(req_input[0]['name'])
    data = dict(dict_key = value)

Now req_input[0]['name'] is the key I would like to insert into the dictionary. Now I know what I'm doint here only creates a dictionary of the form {'dict_key' : value} but I was wondering if it is possible to create the dicionary as to be the form {'Actual value of dict_key' : value}

Regards, Bogdan


The best way to do this is simply using the dict literal {}:

data = {dict_key: value}

Other ways would be

data = dict({dict_key: value})

or

data = dict()
data[dict_key] = value

but these are longer so stay with the first one.


Another way is:

data = {}
data[req_input[0]['name']] = value

This way you can add multiple values to the same dictionary, or loop through req_input if you have multiple parameters there, i.e.:

data = {}
for input in req_input:
    data[input['name']] = value
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜