简体   繁体   中英

creating dictionary where value is key using comprehension

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.

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

  1. i get every key from y with list(y.keys())
  2. if they key is in x i continue else i skip to next key
  3. if above condition is satisfied i control if the key value in y is smalller than 2
  4. if also the above condition is satisfied i create a new item in z with key as key and a list containing y value as value

the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM