python-3.x 如何从两个字典列表中获取特定对象的特定键值?

avwztpqn  于 2022-12-05  发布在  Python
关注(0)|答案(2)|浏览(147)

我有两本字典:

timing = [
    {"day_name": "sunday"},
    {"day_name": "monday"},
    {"day_name": "tuesday"},
    {"day_name": "wednesday"},
    {"day_name": "thursday"},
    {"day_name": "friday"},
    {"day_name": "saturday"},
]

hours_detail = [
    {"day_name": "sunday", "peak_hour": False},
    {"day_name": "monday", "peak_hour": False},
    {"day_name": "tuesday", "peak_hour": False},
    {"day_name": "wednesday", "peak_hour": False},
    {"day_name": "thursday", "peak_hour": False},
    {"day_name": "friday", "peak_hour": False},
    {"day_name": "saturday", "peak_hour": False},

    {"day_name": "saturday", "peak_hour": True},
    {"day_name": "friday", "peak_hour": True},
    {"day_name": "thursday", "peak_hour": True},
]

我想创建另一个字典列表,看起来像下面的一个。我基本上是结合这两个列表,并根据日期名称重新排列。

final_data_object = [
    {
        "timing": {"day_name": "saturday"},
        "hour_detail": [
            {"day_name": "saturday", "peak_hour": False},
            {"day_name": "saturday", "peak_hour": True},
        ]
    },
    {
        "timing": {"day_name": "friday"},
        "hour_detail": [
            {"day_name": "friday", "peak_hour": False},
            {"day_name": "friday", "peak_hour": True},
        ]
    },
    soon on...
]

我试过这个,但没有用:

data = []
for time_instance in timing:
    obj = {
        "timing": time_instance
    }
    for hour_instance in hour_detail:
        if time_instance["day_name"] == hour_instance["day_name"]:
            obj["hour_detail"] = hour_instance
            data.append(obj)

return data
jc3wubiy

jc3wubiy1#

如果pricing = hour_detail,则obj["pricing"]必须是列表,因为它可以有多个值。
你必须在循环for time_instance in timing:中创建一个新的列表,并在每次time_instance["day_name"] == pricing_instance["day_name"]时追加。
示例:

data = []

for time_instance  in timing:
    current_hour_detail = []
    for line in hours_detail:
        if line["day_name"] == time_instance["day_name"]:
            current_hour_detail.append(line)
            
    data.append({
        "timing": time_instance,
        "pricing": current_hour_detail
    })

或更小的方式

data = []

for time_instance  in timing:
    current_hour_detail = [line for line in hours_detail if line["day_name"] == time_instance["day_name"]]
    data.append({
        "timing": time_instance,
        "pricing": current_hour_detail
    })

O(n*m)的时间复杂度,首先通过哈希表{day_name:时间复杂度为O(n + m),所以时间复杂度为O(n+m)

xxhby3vn

xxhby3vn2#

这应该可以回答您的问题:

...
data = []
for time_instance in timing:
    obj = {"timing": time_instance}
    # use a list to store all your pricing
    obj["hour_detail"] = []
    for pricing_instance in pricing:
        if time_instance["day_name"] == pricing_instance["day_name"]:
            obj["hour_detail"].append(pricing_instance)
    # add 'obj' after the loop
    data.append(obj)
print(data)

相关问题