Apoorva Somani
Apoorva Somani

Reputation: 515

I am getting the following error need more than 1 value to unpack

I have the following structure in python.

data_set = {'1':[('Worktype', 'Consultancy'), ('Age', 30), ('Qualification', 'Ph.D'), ('Age', 9)], \
            '2':[('Worktype', 'Service'), ('Age', 21), ('Qualification', 'M.Tech'), ('Age', 1)], \
            '3':[('Worktype', 'Research'), ('Age', 26), ('Qualification', 'M.Tech'), ('Age', 2)], \
           }

I am using the following loop to access the elements. My aim is to print the value associated with 'Worktype'.

for d,c in data_set:
    print(c['Worktype']) 

However, I am getting the following error -

for d,c in data_set:
ValueError: need more than 1 value to unpack

What is the correct way?

Upvotes: 1

Views: 64

Answers (2)

Óscar López
Óscar López

Reputation: 236004

You have two errors. First, you're iterating incorrectly over the key/value pairs (use items() for that). Second, the values are not dictionaries, they're lists of key/value pairs - which can be easily turned into a dictionary using dict(). Try this:

for d, c in data_set.items():
    print(dict(c)['Worktype'])

My approach has the advantage of leaving unmodified the original data set. Now the above will print:

Consultancy
Research
Service

Upvotes: 2

Anand S Kumar
Anand S Kumar

Reputation: 90899

When you iterate over a dictionary directly, it only iterates over its keys . To iterate over the values as well, you should iterate over .items() , even then the inner elements are lists, not dict, so you cannot directly access - c['Worktype'] .

Seems like the inner elements were meant to be a dictionary, if so, you should first convert them into dictionary, by using the dict() built-in function. Example -

data_set = {k:dict(v) for k,v in data_set.items()}
for d,c in data_set.items():
    print(c['Worktype'])

Demo -

>>> data_set = {'1':[('Worktype', 'Consultancy'), ('Age', 30), ('Qualification', 'Ph.D'), ('Age', 9)], \
...             '2':[('Worktype', 'Service'), ('Age', 21), ('Qualification', 'M.Tech'), ('Age', 1)], \
...             '3':[('Worktype', 'Research'), ('Age', 26), ('Qualification', 'M.Tech'), ('Age', 2)], \
...            }
>>>
>>> data_set = {k:dict(v) for k,v in data_set.items()}
>>>
>>> for d,c in data_set.items():
...     print(c['Worktype'])
...
Service
Consultancy
Research

Upvotes: 2

Related Questions