繁体   English   中英

返回修改字典的副本

[英]Return copies of dictionary modified

我有一本字典,对于一个特定的键,我说了5个可能的新值。 因此,我尝试使用一个简单的lambda函数创建原始字典的5个副本,该函数将替换该特定键的值并返回主字典的副本。

# This is the master dictionary.
d = {'fn' : 'Joseph', 'ln' : 'Randall', 'phone' : '100' }
# Joseph has got 4 other phone numbers
lst = ['200', '300', '400', '500']
# I want 4 copies of the dictionary d with these different phone numbers
# Later I would want to do some processing with those dictionary without affecting d

所以我想这样做:

# y is the list I want to hold these copies of dictionaries with modified values
i = d.copy()
y = map( lambda x : (i.update({'phone' : x})) and i, lst )

我以为这将返回一个词典列表,每个词典的电话号码分别变为200,300,400和500。 我可以使用一个简单的方法创建一个循环并创建副本并进行更改,但我想探索并了解如何利用lambdas来实现这一目标。

提前致谢。

您可以使用列表理解:

>>> d = {'fn' : 'Joseph', 'ln' : 'Randall', 'phone' : '100' }
>>> lst = ['200', '300', '400', '500']
>>> [dict(d, phone=x) for x in lst]
[{'ln': 'Randall', 'phone': '200', 'fn': 'Joseph'}, {'ln': 'Randall', 'phone': '300', 'fn': 'Joseph'}, {'ln': 'Randall', 'phone': '400', 'fn': 'Joseph'}, {'ln': 'Randall', 'phone': '500', 'fn': 'Joseph'}]

如果你仍然坚持使用map和lambda(它完全相同,只会慢一点):

>>> map(lambda x: dict(d, phone=x), lst)
[{'ln': 'Randall', 'phone': '200', 'fn': 'Joseph'}, {'ln': 'Randall', 'phone': '300', 'fn': 'Joseph'}, {'ln': 'Randall', 'phone': '400', 'fn': 'Joseph'}, {'ln': 'Randall', 'phone': '500', 'fn': 'Joseph'}]

顺便说一下,你的方法没有按预期工作的原因是因为.update()修改了字典,而不是创建一个反映更新的新字典。 它也不返回结果,因此lambda的计算结果为None (你可能会得到一个像[None, None, None, None]这样的列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM