如何在列表推导中修改字典的值
我有一个字典的列表,而我现在的列表推导式正在分开这些字典(也就是说,创建了新的字典,而不是原来的字典)。下面是一些示例代码,帮助说明这个问题。
list_of_dicts = [{"this": "hi<br>", "that":"bye"}, {"this": "bill", "that":"nye"},{"hello":"kitty<br>", "good bye": "to all of that"}]
所以,你可以看到,我的列表长度是三。每个项目都是一个字典,里面有两个键和两个值。
这是我的列表推导式:
list_of_dicts = [{key: val.replace("<br>", " ")} for dic in list_of_dicts for key, val in dic.items()]
如果你打印这个新行的len()
,你会注意到我现在有六个字典。我相信我想做的事情——也就是把值中的"<br>"
替换成一个空格(" "
)——是可行的,但我不知道怎么做。
到目前为止,我尝试了我知道的每一种方法来创建一个字典,而不是{key: val.method()}
。唯一我没有尝试的是三元列表推导式,因为我觉得那样会太长,根本不想在生产代码中使用。
有什么建议吗?我能在列表推导式中操作一些字典的值,而不改变字典的初始结构吗?
3 个回答
2
在这种情况下,列表推导式可能会让人感到困惑。我建议使用传统的 for
循环:
源代码
data = [{"this": "hi<br>", "that":"bye"}, {"this": "bill", "that":"nye"},{"hello":"kitty<br>", "good bye": "to all of that"}]
for mydict in data:
for key,value in mydict.iteritems():
mydict[key] = value.replace('<br>', '')
print data
输出结果
[{'this': 'hi', 'that': 'bye'}, {'this': 'bill', 'that': 'nye'}, {'hello': 'kitty', 'good bye': 'to all of that'}]
3
你在寻找一种嵌套的理解方式
list_of_dicts = [dict((key, val.replace("<br>", " "))
for key, val in d.iteritems())
for d in list_of_dicts]
不过你把事情搞得比需要的复杂多了……不如试试更简单的:
for d in list_of dicts:
for k, v in d.items():
d[k] = v.replace("<br>", " ")
这样呢?
4
字典推导式被执行了六次,因为你当前的代码实际上是这样的:
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
里的项目各执行一次。