Dictionary comprehension returning ValueError: not enough values to unpack (expected 2, got 1)

Question:

I have a list of dictionaries with hundreds of entries like this

lst = [{'A':'0.1'},{'B':'0.1'},{'C':'0.01'},{'D':'0.0001'},{'E':'0.01'}]

I am trying to sort the key:value pairs into separate lists using dictionary comprehension

lst1 = []
lst2 = []
lst3 = []
lst1.append({key:value for (key,value) in lst if value == '0.1'})
lst2.append({key:value for (key,value) in lst if value == '0.01'})
lst3.append({key:value for (key,value) in lst if value == '0.0001'})

I am then using an if statement to check what list a certain key is in.

variable = 'A'
if variable in lst1:
    print('A is in lst one')

When i run the code I get ValueError: not enough values to unpack (expected 2, got 1)

Asked By: Callum

||

Answers:

This works perfectly!

lst = [{'A':'0.1'},{'B':'0.1'},{'C':'0.01'},{'D':'0.0001'},{'E':'0.01'}]
print(dict([list(d.items())[0] for d in lst if list(d.items())[0][1] == '0.1']))
print(dict([list(d.items())[0] for d in lst if list(d.items())[0][1] == '0.01']))
print(dict([list(d.items())[0] for d in lst if list(d.items())[0][1] == '0.0001']))

output

{'A': '0.1', 'B': '0.1'}
{'C': '0.01', 'E': '0.01'}
{'D': '0.0001'}

thanks to Psidom

Answered By: Callum

First, don’t use list as a name. It’s the name of a built-in class and you don’t want to overwrite it.

What you’re trying to do is something like this:

lst = [{'A':'0.1'},{'B':'0.1'},{'C':'0.01'},{'D':'0.0001'},{'E':'0.01'}]

list1 = [dic for dic in lst if list(dic.values())[0]== '0.1']
list2 = [dic for dic in lst if list(dic.values())[0]== '0.01']
list3 = [dic for dic in lst if list(dic.values())[0]== '0.0001']

print(list1)
print(list2)
print(list3)

outputs:

[{'A': '0.1'}, {'B': '0.1'}]
[{'C': '0.01'}, {'E': '0.01'}]
[{'D': '0.0001'}]

Note that list(dic.values()) wouldn’t have made any sense (it would produce an error) had I overwritten list.

And later:

variable = 'A'
for item in list1:
    if variable in item.keys():
        print('A is in list one')

which can be encapsulated in a function:

def find_key(variable):
    for item in list1:
        if variable in item.keys():
            print(f'{variable} is in list one')

find_key('A')
A is in list one

Now, do you really need to use dictionaries with one key, value pair each one? Do you need to store those in a list? I’m not sure what you’re trying to do, but seems like a XY problem. Try to think whether there is a simpler, more elegant way of doing it.

The same for the second part: are you going to make a separate function for each list?

Answered By: Ignatius Reilly