What is the best way to create a dict
, with some attributes, from another dict
, in Python?
For example, suppose I have the following dict
:
dict1 = { name: 'Jaime', last_name: 'Rivera', phone_number: '111111', email: '[email protected]', password : 'xxxxxxx', token: 'xxxxxxx', secret_stuff: 'yyyyyyy' }
I'd like to obtain
dict2 = { name: 'Jaime', last_name: 'Rivera', phone_number: '111111', email: '[email protected]' }
A dictionary variable can store another dictionary in nested dictionary. The following example shows how nested dictionary can be declared and accessed using python. Here, 'courses' is a nested dictionary that contains other dictionary of three elements in each key.
In Python, you can create a dictionary dict with curly brackets {} , dict() , and dictionary comprehensions.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With