15.8k views
5 votes
In the code below you are given a list of dictionaries which contains a company's employees information. Write a python code that creates a second list of dictionaries (employeess_brief) by extracting only the keys(name,age) from employees.Your program should work for any numbers of elements in the list employees.

employees=[
{
"name":"John doe",
"job":"Software Engineer",
"City":"Mumbai",
"age":"34",
"status":"single"
},
{
"name":"Smith",
"job":"Director",
"city":"New York",
"age":"38",
"status":"Married"
}
]
employees_brief=[]
employees_brief=[{"name":"John doe","age":"34"},{"name":"smith","age":"38"}]

User Gjon
by
7.9k points

1 Answer

4 votes

Final answer:

To create a new list of dictionaries containing only the keys 'name' and 'age' from the given list of dictionaries, you can loop through each dictionary and extract the desired keys and values.

Step-by-step explanation:

To create a second list of dictionaries containing only the keys 'name' and 'age' from the given list of dictionaries, you can loop over each dictionary in the 'employees' list, create a new dictionary with the desired keys and corresponding values, and append it to the 'employees_brief' list.

Here is the Python code to achieve this:

employees = [{'name': 'John Doe', 'job': 'Software Engineer', 'City': 'Mumbai', 'age': '34', 'status': 'single'}, {'name': 'Smith', 'job': 'Director', 'city': 'New York', 'age': '38', 'status': 'Married'}]employees_brief = []

for emp in employees:
brief_info = {'name': emp['name'], 'age': emp['age']}
employees_brief.append(brief_info)

After executing the above code, the 'employees_brief' list will contain dictionaries with only the 'name' and 'age' keys:

employees_brief = [{'name': 'John Doe', 'age': '34'}, {'name': 'Smith', 'age': '38'}]
User FullMoon
by
8.3k points