Return 来自带有生成器函数的嵌套字典的特定值

Return specific values from a nested dictionary with a generator function

我有一个包含嵌套字典的字典列表,如下所示。我想使用生成器和 yield 遍历 reviews 字典列表和 return 所有 rating 给定特定的 user 值。例如 "user" : "A11" 有两个 rating 记录。我想将这些 return 编辑为字典。

data = [{ "product_id" : "123",
    "size" : "L",
    "color" : "blue",
    "reviews" : [
        { "user" : "A11", "rating" : "score1" },
        { "user" : "Z99", "rating" : "score" }] },

    { "product_id" : "987",
    "size" : "M",
    "color" : "red",
    "reviews" : [
        { "user" : "A11", "rating" : "score2" },
        { "user" : "X55", "rating" : "score" }] }
    ]

我有以下生成器,但它基本上是 returning 所有 rating 值而不考虑 user。如何使函数将值过滤为特定的 user

def user_rating(nest, kv):
    if isinstance(nest, list):
        for i in nest:
            for x in user_rating(i, kv):
                yield x
    elif isinstance(nest, dict):
        if kv in nest:
            yield nest[kv]
        for j in nest.values():
            for x in user_rating(j, kv):
                yield x

print(list(user_rating(data, 'rating')))

稍微修改一下就够了:

def user_rating(nest, kv):
    if isinstance(nest, list):
        for i in nest:
            yield from user_rating(i, kv)
    elif isinstance(nest, dict):
        if nest.get('user') == kv: # <----- here
            yield nest # <---- and here
        for j in nest.values():
            yield from user_rating(j, kv)
                
print(list(user_rating(data, 'A11')))
#[{'user': 'A11', 'rating': 'score1'}, {'user': 'A11', 'rating': 'score2'}]

顺便说一句,您可以使用 yield from 来...好吧,从另一个生成器产生收益而不是使用 for 循环