Reputation: 369
I'm trying to generate a dictionary where value is a list using following dictionary of comprehension method.
>>> x = ['a','b','c']
>>> y = {'a':1,'b':2}
>>> z = {i:[].append(j) for (i,j) in y.items() if i in x and j < 2}
>>> z
{'a': None}
I'm trying to get:
{'a':[1]}
Can someone please let me know how to do that? I think I'm getting None as value as it is acting as function and returning None.
Upvotes: 1
Views: 64
Reputation: 1080
Code
x = ['a','b','c']
y = {'a':1,'b':2}
z = {key: [y[key]] for key in list(y.keys()) if key in x and y[key] < 2}
print(z)
output:
{'a': [1]}
Explaination
y
with list(y.keys())
x
i continue else i skip to next keykey
value in y
is smalller than 2key
as key and a list containing y
value as valuethe error rin your code was just that [].append(j)
returned None
so you only ad to do:
z = {i:[j] for (i,j) in y.items() if i in x and j < 2}
another weird thing is to create a list for j
that is a single value, but, becaouse you required it in your expected output and you have surely your reasons to do that, i keeped the output as you wanted, but in general if it is a single value is better to store it directly in the dictand not create a nested list for it in a dict
Upvotes: 1