Skip to main content
 首页 » 编程设计

python之如何在列表理解中改变字典的值

2025年05月04日9think

我有一个字典列表,我当前的列表理解是分离字典(即,在以前没有的地方创建新字典)。下面是一些有助于说明问题的示例代码。

list_of_dicts = [{"this": "hi<br>", "that":"bye"}, {"this": "bill", "that":"nye"},{"hello":"kitty<br>", "good bye": "to all of that"}] 

因此,如您所见,我有一个列表,其 len()是三个。每个项目都是一个包含两个键和两个值的字典。

这是我的列表理解:

list_of_dicts = [{key: val.replace("<br>", " ")} for dic in list_of_dicts for key, val in dic.items()] 

如果你打印 len()在这个新行中,您会注意到我现在有六个 词典。我相信我正在尝试做的事情——即替换 "<br>"在带有一个空格的值中 ( " " ) - 是可能的,但我不知道如何。

到目前为止,我已经尝试了所有我知道的方法来创建字典而不是 {key: val.method()} .我唯一没有尝试过的是三元列表理解,因为我可以看到它太长了,我永远不想在生产代码中使用它。

有什么见解吗?我可以在不影响字典初始结构的情况下在列表理解中操纵某些字典的值吗?

请您参考如下方法:

字典理解被执行了六次,因为你当前的代码等同于:

list_of_dicts = [{"this": "hi<br>", "that":"bye"}, {"this": "bill", "that":"nye"},{"hello":"kitty<br>", "good bye": "to all of that"}] 
tmp = [] 
 
for dic in list_of_dicts: 
    for key, val in dic.items(): 
        tmp.append({key: val.replace("<br>", " ")}) 
 
list_of_dicts = tmp 

外循环将运行三次,因为 list_of_dicts 有三个项目。对于外循环的每次迭代,内循环将运行两次,因为 list_of_dicts 中的每个字典都有两个项目。总之,这一行:

tmp.append({key: val.replace("<br>", " ")}) 

将被执行六次。


您可以通过简单地移动字典理解中的 for key, val in dic.items() 子句来解决这个问题:

>>> list_of_dicts = [{"this": "hi<br>", "that":"bye"}, {"this": "bill", "that":"nye"},{"hello":"kitty<br>", "good bye": "to all of that"}] 
>>> [{key: val.replace("<br>", " ") for key, val in dic.items()} for dic in list_of_dicts] 
[{'this': 'hi ', 'that': 'bye'}, {'this': 'bill', 'that': 'nye'}, {'hello': 'kitty ', 'good bye': 'to all of that'}] 
>>> 

现在,字典理解只会执行三次:list_of_dicts 中的每个项目一次。