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.