gpt4 book ai didi

python - 返回已修改字典的副本

转载 作者:太空狗 更新时间:2023-10-30 01:47:02 24 4
gpt4 key购买 nike

我有一本字典,对于一个特定的键,我说了 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。我可以放置一个循环并创建副本并使用天真的方法更改它们,但我想探索并了解如何利用 lambda 来完成此操作。

提前致谢。

最佳答案

您可以使用列表理解:

>>> 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()就地修改字典,而不是创建反射(reflect)更新的新字典。它也不返回结果,因此 lambda 的计算结果为 None (你可能会得到类似 [None, None, None, None] 的列表。

关于python - 返回已修改字典的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9589466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com