[英]Return copies of dictionary modified
I have a dictionary and for a particular key, I have say 5 possible new values. 我有一本字典,对于一个特定的键,我说了5个可能的新值。 So I am trying to create 5 copies of the original dictionary by using a simple lambda function that will replace the value of that particular key and return a copy of the master dictionary. 因此,我尝试使用一个简单的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
So I am trying to do this: 所以我想这样做:
# 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 )
I thought this would return a list of dictionaries and each of them would have phone number changed to 200, 300, 400 and 500 respectively. 我以为这将返回一个词典列表,每个词典的电话号码分别变为200,300,400和500。 I can put a loop and create copies and change them using a naive approach, but I want to explore and know how I can exploit the lambdas to accomplish this. 我可以使用一个简单的方法创建一个循环并创建副本并进行更改,但我想探索并了解如何利用lambdas来实现这一目标。
Thanks in advance. 提前致谢。
You can use a list comprehension: 您可以使用列表理解:
>>> 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'}]
If you still insist on using map
and a lambda (which does exactly the same, only a bit slower): 如果你仍然坚持使用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'}]
By the way, the reason why your approach didn't work as expected is because .update()
modifies the dictionary in place, rather than creating a new dictionary that reflects the update. 顺便说一下,你的方法没有按预期工作的原因是因为.update()
修改了字典,而不是创建一个反映更新的新字典。 It also doesn't return the result, so the lambda evaluates to None
(and you probably got back a list like [None, None, None, None]
. 它也不返回结果,因此lambda的计算结果为None
(你可能会得到一个像[None, None, None, None]
这样的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.