Python - 将列表中的项设置为字典值列表

时间:2017-01-26 17:00:10

标签: python list dictionary

鉴于list

links = [ 'link1', 'link2', 'link3', 'link3', 'link4', 'link5', 'link6', 'link6', 'link7', 'link8', 'link9', 'link10']

dicts列表:

 sources =  [{'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}]

我想将每个src值设置为其对应的链接,如下所示:

{'src': 'link1'}, {'src': 'link2'} ...

我试过了:

for s in sources:
    for l in links:
        s['src'] = l
        print (s)

但这可以完成10次,而且我只想完成一次。

如何使用单线程实现这一目标?

3 个答案:

答案 0 :(得分:4)

我认为src中有其他内容,否则sources没有意义:

for src, link in zip(sources, links):
    src['src'] = link

可以将其写成一行:

[s.update({'src': x }) for s, x in zip(sources, links)]

但这可能是所谓的“副作用的理解”,并被大多数蟒蛇认为是不好的味道。一个循环更加pythonic。

以上也假设len(sources)==len(links)另有考虑:

for src, link in zip(sources, itertools.cycle(links)):
    src['src'] = link

将以循环方式填充链接。

如果这些src dicts实际上是空的,则无需保留它们的列表,只需从头开始创建它:

 sources = [{'src': x} for x in links]

答案 1 :(得分:2)

我不会在这里建议一个单行。只需一个简单的for循环就可以了:

>>> for d,link in zip(sources, links):
...     d['src'] = link
>>> print(sources)
[{'src': 'link1'}, {'src': 'link2'}, {'src': 'link3'}, {'src': 'link3'}, {'src': 'link4'}, {'src': 'link5'}, {'src': 'link6'}, {'src': 'link6'}, {'src': 'link7'}, {'src': 'link8'}]

答案 2 :(得分:2)

links = [ 'link1', 'link2', 'link3', 'link3', 'link4', 'link5', 'link6', 'link6', 'link7', 'link8', 'link9', 'link10']

sources = [dict(src = ln) for ln in links]
print sources

[{'src': 'link1'}, {'src': 'link2'}, {'src': 'link3'}, {'src': 'link3'}, {'src': 'link4'}, {'src': 'link5'}, {'src': 'link6'}, {'src': 'link6'}, {'src': 'link7'}, {'src': 'link8'}, {'src': 'link9'}, {'src': 'link10'}]

print map(lambda v: dict(src = v), links)

# for python 3
print (list(map(lambda v: dict(src = v), links)))

[{'src': 'link1'}, {'src': 'link2'}, {'src': 'link3'}, {'src': 'link3'}, {'src': 'link4'}, {'src': 'link5'}, {'src': 'link6'}, {'src': 'link6'}, {'src': 'link7'}, {'src': 'link8'}, {'src': 'link9'}, {'src': 'link10'}]