3

I have 2 lists, A and B.

  • A is list of dictionaries which contain list of values.
  • B is a simple list.

Requirement is to add the elements of list B into dictionary values of A.

Below is the code,

a = [{'a':[1,5]}, {'b' : [6,10]}, {'c' : [11,15]}]
b = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

for i in a:
  for k,j in i.items():
      for m,n in enumerate(b):
          if j[0]<= n<=j[1]:
              j.append(n)

print(a)

[{'a':[1,5,1,2,3,4,5]}, {'b' : [6,10,6,7,8,9,10]}, {'c' : 
[11,15,11,12,13,14,15]}]

# tried list comprehension
a= [{k:n} for i in a for k,j in i.items() for m,n in enumerate(b)
if j[0]<= n<=j[1]]

print(a)

[{'a': 1}, {'a': 2}, {'a': 3}, {'a': 4}, {'a': 5}, {'b': 6}, {'b': 7}, 
{'b': 8}, {'b': 9}, {'b': 10}, {'c': 11}, {'c': 12}, {'c': 13}, {'c': 
14}, {'c': 15}]

Question is whether this can be done using list comprehension? I have tried but unable to generate the required output.

2 Answers 2

3
a = [{k: [ x for x in b if v[0] <= x <= v[1] ]} for d in a for k,v in d.items()]
Sign up to request clarification or add additional context in comments.

Comments

2

Just a small modification of the @Błotosmętek answer to get exactly what you need as output.

a = [{'a': [1, 5]}, {'b': [6, 10]}, {'c': [11, 15]}]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

a = [{k: v+[x for x in b if v[0]<=x<=v[1]]} for d in a for k, v in d.items()]
print(a)

Output

[{'a': [1, 5, 1, 2, 3, 4, 5]}, {'b': [6, 10, 6, 7, 8, 9, 10]}, {'c': [11, 15, 11, 12, 13, 14, 15]}]

2 Comments

Thanks for the modified solution
Wasn't obvious from the description, but if we take OP's solution as reference then yes, your modification is necessary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.