简体   繁体   English

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

[英]How to append a dictionary as a value of a key in another dictionary?

I have a dictionary: 我有一本字典:

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

i want that it will be the value of firstKey in my second payload 我希望它将是第二个有效载荷中firstKey的值

i tried it 我尝试过这个

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

i want to have something like this 我想要这样的东西

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

UPDATE 1 更新1

and i tried 我试过了

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

and sent it in a form with FormRequest, but it was sent like 并以FormRequest的形式发送,但发送方式为

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

UPDATE 2 更新2

I send my query in Scrapy like this 我像这样在Scrapy中发送查询

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

Just add it to the dictionary normally using the variable name accessToken as the value: 通常只需使用变量名称accessToken作为值将其添加到字典中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'}}
>>> 
{'firstKey': accessToken }

is perfectly ok. 完全可以。 You can also add more keys and values if needed 如果需要,您还可以添加更多键和值

You can simply use: 您可以简单地使用:

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

In python, dictionary values can be of any type, including a dictionary. 在python中,字典值可以是任何类型,包括字典。

Why don't you just add a key to the dictionary with a dictionary as its value, ie: 您为什么不只是以字典作为值将字典添加到字典,即:

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

d1["key5"] = d2

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

I resolved my problem by changing 我通过改变解决了我的问题

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM