Parsing Python dictionary with multiple objects

Rustom Mody rustompmody at gmail.com
Wed Oct 15 18:06:25 CEST 2014


On Wednesday, October 15, 2014 9:22:48 PM UTC+5:30, Anurag Patibandla wrote:
> Thanks Rustom for the advice.
> I am new to Python and getting struck at some basic things. How do I assign the values that I am printing to 3 variables say dict1, dict2, dict3?
> When I try to assign them before the print statement like this:
> d1, d2, d3 =[(queues[j], json.get(queues[j])) for j in range(len(queues))]

> I get an error saying 'need more than one value to unpack'

Probably means your comprehension

[(queues[j], json.get(queues[j])) for j in range(len(queues))]

is having less than 3 values

>>> lst = [1,2,3]
>>> x,y,z = lst
>>> (x,y,z) # note no need to print
(1, 2, 3)
>>> lst=[1]
>>> x,y,z=lst
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
>>> lst=[1,2,3,4]
>>> x,y,z=lst
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
================

I suggest youdont directly start with multiple assignment
Instead do it in two steps

dicts = [(queues[j], json.get(queues[j])) for j in range(len(queues))]

d0 = dicts[0]
d1 = dicts[1]
d2 = dicts[2]

When that works go to the more compact form

Also please get rid of the range(len(queues))
Its unpythonic!



More information about the Python-list mailing list