如何在另一个字典中附加字典作为键的值?

时间:2017-05-23 17:19:58

标签: python dictionary scrapy

我有一本字典:

accessToken = {'acces' : self.access , 'expires_in' :self.expires}

我希望它在我的第二个有效载荷中 firstKey 的值

我试过了

payload     =  {"firstKey" : json.dumps(accessToken) , "encodingVersion" : "1",
                "headerVersion" : "3" , "username" : username }

我希望有这样的东西

{'firstKey': {'acces' : self.access , 'expires_in' :self.expires},"encodingVersion" : "1",
  "headerVersion" : "3" , "username" : username }

更新1

我试过

payload     =  {"firstKey" : accessToken , "encodingVersion" : "1",
                "headerVersion" : "3" , "username" : username }

并以FormRequest的形式发送,但它像

一样发送

headerVersion=3&username=usernameValue&encodingVersion=1&firstKey=selfaccess_value&firstKey=self_expires_value

更新2

我在 Scrapy 中发送我的查询

yield  FormRequest(link, method="POST", formdata=payload
                          , callback=self.myFunction)

5 个答案:

答案 0 :(得分:1)

通常使用变量名accessToken作为值将其添加到字典中:

>>> accessToken = {'acces' : "self.access" , 'expires_in' :"self.expires"}
>>> payload     =  {"firstKey" : accessToken , "encodingVersion" : "1",
...                 "headerVersion" : "3" , "username" : "username" }
>>> 
>>> payload
{'headerVersion': '3', 'username': 'username', 'encodingVersion': '1', 'firstKey': {'acces': 'self.access', 'expires_in': 'self.expires'}}
>>> 

答案 1 :(得分:1)

{'firstKey': accessToken }

完全没问题。您还可以根据需要添加更多键和值

答案 2 :(得分:0)

您可以简单地使用:

payload     =  {"firstKey" : accessToken , "encodingVersion" : "1",
                "headerVersion" : "3" , "username" : username }

在python中,字典值可以是任何类型,包括字典。

答案 3 :(得分:0)

为什么不在字典中添加一个字符作为其值,即:

d1 = {"key1": "val1", "key2": "val2"}
d2 = {"key3": "val3", "key4": "val4"}

d1["key5"] = d2

print(d1)
{"key1": "val1", "key2": "val2", "key5": {"key3": "val3", "key4": "val4"}}

答案 4 :(得分:0)

我通过更改

解决了我的问题
yield  FormRequest(link,headers=headers, formdata=payload, meta = meta ,  method="POST"
                          , callback=self.myFunction)

yield  FormRequest(link,headers=headers, body=str(payload), meta = meta ,  method="POST"
                          , callback=self.myFunction)
相关问题