python 要过滤的列表中的字典键 - python
python dict key in list to filter - python
a = [{"price": 1,"id": 1},{"price": 8.2, "id": 2}, {"price": 10.99,"id": 3}]
user = ['price', 'abc']
输出应该是:
output = [{"price": 1},{"price": 8.2}, {"price": 10.99}]
场景是 dict a keys 应该被 user list
过滤
您可以使用列表理解
[{u: val_a.get(u) for u in user if val_a.get(u)} for val_a in a]
嵌套理解可能并不理想,上面的示例对值进行了两次检查。通过循环构建结果可能会给出最直接的结果并且同时可读:
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)
您可以使用集合交集操作来获取要保留的键:
result = [{k: d[k] for k in set(d.keys()).intersection(set(user))} for d in a]
print(result)
这会打印:
[{'price': 1}, {'price': 8.2}, {'price': 10.99}]
a = [{"price": 1,"id": 1},{"price": 8.2, "id": 2}, {"price": 10.99,"id": 3}]
user = ['price', 'abc']
输出应该是:
output = [{"price": 1},{"price": 8.2}, {"price": 10.99}]
场景是 dict a keys 应该被 user list
过滤您可以使用列表理解
[{u: val_a.get(u) for u in user if val_a.get(u)} for val_a in a]
嵌套理解可能并不理想,上面的示例对值进行了两次检查。通过循环构建结果可能会给出最直接的结果并且同时可读:
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)
您可以使用集合交集操作来获取要保留的键:
result = [{k: d[k] for k in set(d.keys()).intersection(set(user))} for d in a]
print(result)
这会打印:
[{'price': 1}, {'price': 8.2}, {'price': 10.99}]