簡體   English   中英

理解嵌套的 python 字典理解

[英]understanding nested python dict comprehension

我正在與 dict 理解相處並試圖了解以下 2 個 dict 理解是如何工作的:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM