Python 中的字典列表理解

Dict list comprehension in Python

我是 python 新手。我正在努力学习理解,目前我被困在这个场景中。我可以做这个突变

sample_dict_list = [{'name': 'Vijay', 'age':30, 'empId': 1}, {'name': 'VV', 'age': 10, 'empId': 2},
                    {'name': 'VV1', 'age': 40, 'empId': 3}, {'name': 'VV2', 'age': 20, 'empId': 4}]
def list_mutate_dict(list1, mutable_func):
    for items in list1:
        for key,value in items.items():
            if(key == 'age'):
                items[key] = mutable_func(value)
    return
mutable_list_func = lambda data: data*10
list_mutate_dict(sample_dict_list, mutable_list_func)
print(sample_dict_list)

[{'name': 'Vijay', 'age': 300, 'empId': 1}, {'name': 'VV', 'age': 100, 'empId': 2}, {'name': 'VV1', 'age': 400, 'empId': 3}, {'name': 'VV2', 'age': 200, 'empId': 4}]

只有键'age'的字典被变异并返回

这很好用。但我正在尝试对单行理解进行同样的尝试。我不确定是否可以完成。

print([item for key,value in item.items() if (key == 'age') mutable_list_func(value) for item in sample_dict_list])

THis is the op - [{'age': 200}, {'age': 200}, {'age': 200}, {'age': 200}] which is incorrect. It just takes in the last value and mutates and returns as a dict list

这可以在“嵌套”列表字典理解中完成吗?

使用推导式时,您实际上是在创建一个新的推导式,因此“变异”不在上下文中。但假设您想要相同的输出:

mutable_func = lambda data: data*10

print([{**d, "age": mutable_func(d["age"])} for d in sample_dict_list])

在我的示例中,您使用 **d 解压字典并添加另一个键值,该键值将覆盖 d.

中的现有键值

有点复杂但是这里:

def list_mutate_dict(list1, mutable_func):
    [{key: (mutable_func(value) if key == 'age' else value) for key, value in item.items()} for item in list1]

解释(由内而外):

首先,如果需要,您可以在赋值内的条件中更改值,同时保持所有其他值相同。
然后,您通过迭代所有项目对所有字典项目执行此操作。
最后,您对列表中的所有词典执行此操作。

我要补充一点,这些类型的列表理解不被认为是最佳实践,并且通常会导致非常混乱和难以维护的代码。