Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create dictionary from another dictionary?

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]' } 
like image 893
Jaime Rivera Avatar asked Aug 24 '12 21:08

Jaime Rivera


People also ask

Can a dictionary have another dictionary?

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.

Can I make a dictionary of dictionaries in Python?

In Python, you can create a dictionary dict with curly brackets {} , dict() , and dictionary comprehensions.


2 Answers

For instance:

keys = ['name', 'last_name', 'phone_number', 'email'] dict2 = {x:dict1[x] for x in keys} 
like image 86
Lev Levitsky Avatar answered Sep 24 '22 00:09

Lev Levitsky


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} 
like image 38
Rostyslav Dzinko Avatar answered Sep 23 '22 00:09

Rostyslav Dzinko