a = [{"price": 1,"id": 1},{"price": 8.2, "id": 2}, {"price": 10.99,"id": 3}]
user = ['price', 'abc']
output supposed to be:
output = [{"price": 1},{"price": 8.2}, {"price": 10.99}]
The scenario is that dict a keys should be filtered by user list
CodePudding user response:
You can use list comprehension
[{u: val_a.get(u) for u in user if val_a.get(u)} for val_a in a]
Nested comprehensions may not be desirable and the above example checks twice for the value. Building your results by a loop may give the most straightforward result and be readable at the same time:
results = []
for val_a in a:
result = {}
for u in user:
u_val = val_a.get(u)
if u_val:
result.update({u: u_val})
results.append(result)
Python3.8 :
results = []
for val_a in a:
result = {}
for u in user:
if u_val := val_a.get(u)
result.update({u: u_val})
results.append(result)
CodePudding user response:
You can use a set intersection operation to get the keys to retain:
result = [{k: d[k] for k in set(d.keys()).intersection(set(user))} for d in a]
print(result)
This prints:
[{'price': 1}, {'price': 8.2}, {'price': 10.99}]