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

Create a list of dictionaries from a global variable using map or comprehension list python

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

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

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

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

我可以用下面的代码来完成:

result_list = []
for word in words:
    dictionary_to_add = GLOBAL.copy()
    dictionary_to_add["second"] = word
    result_list.append(dictionary_to_add)

我的问题是如何使用理解列表或使用 map() 函数来做到这一点

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)

测试它,然后再尝试。

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'}]

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

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

甚至更好(仅Python 3)

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