Nested list

I have 2 lists, A and B.

  • A is a list of dictionaries containing a list of values.
  • B is a simple list.

The requirement is to add the elements of list B to the 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}]

      

The question is, can this be done using a list comprehension? I tried but was unable to generate the required output.

+3


source to share


2 answers


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

      



+3


source


Just a slight modification to @ Błotosmętek's answer to get exactly what you need for the 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


source







All Articles