如何将已定义的变量和值放入Python dict?

时间:2013-08-04 16:53:11

标签: python json serialization dictionary python-requests

我有这段代码:

if 'instagramTV' in path:
    self.send_response(200)
    instaShortcode, LTV, EMAIL, TIME, userID, URL  = map(\
    qs.get, ['instaID', 'channelID', 'uEmail', 'Time', 'uID', 'contentUrl'])

    channelID, uEmail, instagramShortcode, uTime, uID, contentUrl = map(\
    lambda x : str(x)[2:-2], [LTV, EMAIL, instaShortcode, TIME, userID, URL])

    for i in (channelID, uEmail, instagramShortcode, uTime, uID, contentUrl):
        print i
    instaSTEP2 = requests.get("http://api.instagram.com/oembed?url=http://instagr.am/p/%s/"% instagramShortcode).json()
    instaMeID = instaSTEP2['media_id']
    instaINFO = requests.get("https://api.instagram.com/v1/media/%s?accesstoken=295391286.1b882b8.33fa51373fae4885b5c60ceb186e6560" % instaMeID).json()
    print instaINFO['data']['user']['profile_picture']
    print instaINFO['data']['user']['username']
    print instaINFO['data']['caption']['text']
    print instaINFO['data']['images']['standard_resolution']['url']
    ltvMSG = {'fromEMAIL': 'uEmail', 'toCHANNELID': 'channelID', 'timeSENT': 'uTime', 'profiePIC': "instaINFO['data']['user']['profile_picture']",'userNAME': "instaINFO['data']['user']['username']", 'msgBODY': "instaINFO['data']['caption']['text']", 'msgIMAGE': "instaINFO['data']['images']['standard_resolution']['url']"}
    print ltvMSG

第一个vars来自一个http get请求,然后我使用其中一些vars进行api调用,然后我找回一些json。

我正在尝试将来自get请求的一些初始变量和来自api调用的一些值放入我自己的dict / json中,最终将进入redis列表。

print ltvMSG返回:

{'userNAME': "instaINFO['data']['user']['username']", 'timeSENT': 'uTime', 'msgIMAGE': "instaINFO['data']['images']['standard_resolution']['url']", 'msgBODY': "instaINFO['data']['caption']['text']", 'fromEMAIL': 'uEmail', 'toCHANNELID': 'channelID', 'profilePIC': "instaINFO['data']['user']['profile_picture']"}

这是我想要的结构,但是如何使实际值显示为键的值。

1 个答案:

答案 0 :(得分:1)

您正在做的是将这些字符串文字添加到dict中。所以,如果,而不是:

     loqootvMSG = {'fromEMAIL': 'uEmail', 'toCHANNELID': 'channelID', 'timeSENT': 'uTime', 'profilePIC': "instaINFO['data']['user']['profile_picture']",'userNAME': "instaINFO['data']['user']['username']", 'msgBODY': "instaINFO['data']['caption']['text']", 'msgIMAGE': "instaINFO['data']['images']['standard_resolution']['url']"}

你这样做:

     loqootvMSG = {'fromEMAIL': uEmail, 'toCHANNELID': channelID, 'timeSENT': uTime, 'profilePIC': instaINFO['data']['user']['profile_picture'],'userNAME': instaINFO['data']['user']['username'], 'msgBODY': instaINFO['data']['caption']['text'], 'msgIMAGE': instaINFO['data']['images']['standard_resolution']['url']}

例如,它会存储uEmail的值,而不是字符串'uEmail'