Friday, May 27, 2022

Python: valueerror too many values to unpack (expected 2) stackoverflow - dict to tuples

Admittedly, I haven't spent a lot of time in Python lately and find myself hitting my head on the wall trying to figure out some fairly simple things again. This is one of those such things.

Problem: 

I am using the requests library to interact with a server. This library has some great methods to prepare requests and then be able to send them at a later time. In one of these instances, I was building and preparing the Request with some data (also wrapping with the session to preserve cookie info):

request = session.prepare_request(Request('GET', "https://example.com/search", params=rdata))

The rdata object looks like a simple dict with key/value pairs. However, when running the code I got the error: 

ValueError: too many values to unpack (expected 2)


Solution:

After printing out the object and comparing it with a clean object, I found the issue:

rdata = {'key': 1, 'value': 2},

The comma at the end implied to Python that my structure was a tuple (pseudo: type(rdata) == <class 'tuple'>). Also, keep in mind my variable has a lot more data in it running it off the screen and I am not using word-wrap... so out of site, out of mind I guess. 

After removing the comma, rdata was seen as a dict again and could be converted to a list of tuples by requests prepare function. 

No comments: