簡體   English   中英

python 需要在字典列表上迭代列表

[英]python need to iterate a list over a list of dicts

a=['May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'January', 'February']

b=[ {'actualscore1': 550, 'forecastedScore1': 33, 'unit': 'u2', 'account': 'a2', 'domain': 'd2', 'location': 'l2', 'year': 2021, 'month': 'October'},
{'actualscore1': 550, 'forecastedScore1': 34, 'unit': 'u1', 'account': 'A1', 'domain': 'd1', 'location': 'l1', 'year': 2021, 'month': 'November'}]

python 需要在字典列表上迭代列表

我需要在 dict b列表上迭代列表a是否存在值。 如果存在,則從b中獲取一些值,如果在 9 月之前的月份中未輸入 0,則應顯示為 0,對於 12 月、1 月和 2 月,應顯示為 0

我的 output 應該是

output=[0,0,0,0,0,{'actualscore1': 550, 'forecastedScore1': 33,'month': 'October'},{'actualscore1': 550, 'forecastedScore1': 34,'month': 'November'},0,0,0]

只需遍歷您的數據結構並從中獲取您需要的數據:

output = []
for month in a:
    for d in b:
        if d["month"] == month:
            output.append({
                "actualscore1": d["actualscore1"], 
                "forecastedScore1": d["forecastedScore1"],
                "month": month,
            })
            break
    else:
        output.append(0)

使用列表理解的方法:

keys = ['actualscore1', 'forecastedScore1', 'month'] # keys to extract
output = [next(({k: dct[k] for k in keys} for dct in b if dct['month'] == month), 0) for month in a]
print(output)
# [0, 0, 0, 0, 0, {'actualscore1': 550, 'forecastedScore1': 33, 'month': 'October'}, {'actualscore1': 550, 'forecastedScore1': 34, 'month': 'November'}, 0, 0, 0]

您可以單行執行此操作,例如:

output = [next((d for d in b if month==d['month']), 0) for month in a]

暫無
暫無

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

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