理解嵌套 python 字典理解

understanding nested python dict comprehension

我正在接受 dict comprehensions 并试图了解以下 2 个 dict comprehensions 的工作原理:

select_vals = ['name', 'pay']
test_dict = {'data': [{'name': 'John', 'city': 'NYC', 'pay': 70000}, {'name': 'Mike', 'city': 'NYC', 'pay': 80000}, {'name': 'Kate', 'city': 'Houston', 'pay': 65000}]}
dict_comp1 = [{key: item[key] for key in select_vals } for item in test_dict['data']  if item['pay'] > 65000 ]

上面一行让我明白了 [{'name': 'John', 'pay': 70000}, {'name': 'Mike', 'pay': 80000}]

dict_comp2 = [{key: item[key]} for key in select_vals  for item in test_dict['data']  if item['pay'] > 65000 ]

上面一行让我明白了 [{'name': 'John'}, {'name': 'Mike'}, {'pay': 70000}, {'pay': 80000}]

写在 for 循环中时,这两个 o/ps 有何不同?当我在 for 循环中执行时

dict_comp3 = []
for key in select_vals:
    for item in test_dict['data']:
        if item['pay'] > 65000:
            dict_comp3.append({key: item[key]})

print(dict_comp3)

上面一行让我和dict_comp2一样 [{'name': 'John'}, {'name': 'Mike'}, {'pay': 70000}, {'pay': 80000}]

如何在 for 循环中得到 o/p 作为 dict_comp1?

select vals 迭代应该是内部迭代

result = []
for item in test_dict['data']:
    if item['pay'] > 65000:
        aux = {}
        for key in select_vals:
            aux[key] = item[key]
        result.append(aux)