Return copies of the modified dictionary

I have a dictionary for a specific key, I say 5 possible new values. Therefore, I am trying to create 5 copies of the original dictionary using a simple lambda function that will replace the value of this particular key and return a copy of the main 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 change the phone number to 200, 300, 400, and 500, respectively. I can put a loop and create copies and modify them using a naive approach, but I want to research and know how I can use lambda to achieve this.

Thanks in advance.

+4
source share
1 answer

You can use 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 lambda (which does the same thing, only a little 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 your approach did not work properly is because .update() modifies the dictionary in place, rather than creating a new dictionary that reflects the update. It also does not return a result, so the lambda evaluates to None (and you probably returned a list like [None, None, None, None] .
+14
source

Source: https://habr.com/ru/post/1400072/


All Articles