BCS*_*BCS 12 python dictionary list-comprehension
给定:
template = {'a': 'b', 'c': 'd'}
add = ['e', 'f']
k = 'z'
Run Code Online (Sandbox Code Playgroud)
我想使用list comprehension来生成
[{'a': 'b', 'c': 'd', 'z': 'e'},
{'a': 'b', 'c': 'd', 'z': 'f'}]
Run Code Online (Sandbox Code Playgroud)
我知道我可以这样做:
out = []
for v in add:
t = template.copy()
t[k] = v
out.append(t)
Run Code Online (Sandbox Code Playgroud)
但它有点冗长,没有我想要取代的优势.
unu*_*tbu 19
[dict(template,z=value) for value in add]
Run Code Online (Sandbox Code Playgroud)
或(使用k):
[dict(template,**{k:value}) for value in add]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4799 次 |
| 最近记录: |