使用map或comprehension list python从全局变量创建字典列表

时间:2017-09-30 06:37:33

标签: python python-3.x dictionary list-comprehension map-function

我有一个字典作为全局变量和一个字符串列表:

benchmark.js

我的目标是创建以下列表:

GLOBAL = {"first": "Won't change", "second": ""}
words = ["a", "test"]

我可以使用以下代码执行此操作:

[{"first": "Won't change", "second": "a"}, {"first": "Won't change", "second": "test"}]

我的问题是如何使用理解列表或使用map()函数

来完成

3 个答案:

答案 0 :(得分:2)

非常确定你可以在一条丑陋的线条中做到这一点。假设你使用不可变量作为值,否则你必须进行深度复制,这也是可能的:

[GLOBAL.copy().update(second=w) for w in word]

甚至更好(仅限Python 3)

[{**GLOBAL, "second": w} for w in word]

答案 1 :(得分:1)

GLOBAL = {"first": "Won't change", "second": ""}
words = ["a", "test"]
result_list = []
for word in words:
    dictionary_to_add = GLOBAL.copy()
    dictionary_to_add["second"] = word
    result_list.append(dictionary_to_add)
print result_list
def hello(word):
    dictionary_to_add = GLOBAL.copy()
    dictionary_to_add["second"] = word
    return dictionary_to_add
print [hello(word) for word in words]
print map(hello,words)

测试它,并尝试更多。

答案 2 :(得分:1)



In [106]: def up(x):
     ...:     d = copy.deepcopy(GLOBAL)
     ...:     d.update(second=x)
     ...:     return d
     ...: 

In [107]: GLOBAL
Out[107]: {'first': "Won't change", 'second': ''}

In [108]: map(up, words)
Out[108]: 
[{'first': "Won't change", 'second': 'a'},
 {'first': "Won't change", 'second': 'test'}]