簡體   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