使用MAP或理解列表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.copy().update(second=w) for w in word]

甚至更好(仅Python 3)

[{**GLOBAL, "second": w} for w in word]
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'}]

相关内容