0

What is the best way to store a string variable as a string value in a dictionary?

Below I am trying to put a string variable named authToken and place it in the dictionary called header so I can call it using the requests module

if currentTime >= authExpTime: getAuthToken() else: header = {'Content-Type':'application/json','Authorization':'OAUTH2 access_token=authToken'} print header for i in metricsCollected: callURL = apiURL + i + "?samepletime=" print callURL apiResponse = requests.get(apiURL, headers=header) apiResponse.json() 
4
  • It seems like you are asking how to get the value of authToken into the string that is the value of the 'Authorization' key. Is this what you are asking? Commented Mar 11, 2016 at 18:12
  • I don't quite understand what you're asking here. Could you elaborate? Commented Mar 11, 2016 at 18:12
  • @hlongmore that is exactly it :) Commented Mar 11, 2016 at 18:14
  • @That1Guy I think he has a key/value pair (OAUTH2 access_token=authToken) within another key/value pair ('Authorization':'OAUTH2 access_token=authToken'). A nested dictionary ({"OAUTH2 access_token" : "authToken"}) would be better but I didn't know whether his script would allow that or not. Commented Mar 11, 2016 at 18:16

2 Answers 2

3

There are many ways you could do this. Some are more pythonic than others. The way I would probably do it is:

header = { 'Content-Type': 'application/json', 'Authorization': 'OAUTH2 access_token=%s' % (authToken) } 
Sign up to request clarification or add additional context in comments.

1 Comment

I think this is better than my answer since it avoids the confusion/inefficiencies of += for string operations.
1

Like so?

if currentTime >= authExpTime: getAuthToken() else: header = {'Content-Type':'application/json','Authorization':'OAUTH2 access_token='} header["Authorization"] += authToken print header for i in metricsCollected: callURL = apiURL + i + "?samepletime=" print callURL apiResponse = requests.get(apiURL, headers=header) apiResponse.json() 

1 Comment

Thanks everyone! much appreciated ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.