How do I create dictionary from another dictionary?
for key in d1:
if key in wanted_keys:
d2[key] = d1[key]
update
I recently figured out that there's a much cleaner way of doing that with dict
comprehensions
wanted_keys = set(['this_key', 'that_key'])
new_dict = {k: d1[k] for k in d1.keys() & wanted_keys}
For instance:
keys = ['name', 'last_name', 'phone_number', 'email']
dict2 = {x:dict1[x] for x in keys}
Using dict comprehension:
required_fields = ['name', 'last_name', 'phone_number', 'email']
dict2 = {key:value for key, value in dict1.items() if key in required_fields}