简体   繁体   中英

Return copies of dictionary modified

I have a dictionary and for a particular key, I have say 5 possible new values. 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.

# 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. 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.

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 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. 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] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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