Home > database >  How to extract the given keys in one dictionary from another into a new dictionary (Python)
How to extract the given keys in one dictionary from another into a new dictionary (Python)

Time:11-17

I'm trying to practice sets and dictionaries, and one thing I've been finding is myself stuck on this practice problem over and over.

For example if I have a dictionary like

employees =[
{
    "name": "Jamie Mitchell",
    "job": "Head Chef",
    "city": "Toronto",
    "age": 80,
    "status": "Working"
},
{
    "name": "Michell Anderson",
    "job": "Line Cook",
    "city": "Mississauga",
    "age": 56,
    "status": "Lunch Break"
  }
]

How would I extract the second part of the dictionary from the first in order to only have the information on the right be in a new dictionary?

I'm trying something like:

extractedInfo = []

for employee in employees:
    for key in keys:
        extractedInfo.append(employee[key])

newDict = {extractedInfo[i]: extractedInfo[i   1] for i in range(0, len(extractedInfo), 2)}
print(newDict)

New Dictionary would look like : (Jamie, Chef, Toronto , 80 , Working , Michell , Line Cook, Mississauga, 56 , Lunch Break)

However I know I'm doing something wrong, as I'm not sure what to initialize "Keys" as. I'm new to dictionaries and sets and I'm having a hard time. Any suggestions or tips on a way to do this would help a lot.

EXTRA: What if I wanted to only keep Name and Job values of both employees?

CodePudding user response:

You have them backwards; the outer one [] is a list. The inner ones {} are dictionaries.

You can get the second one with employees[1] (indexing starts from 0) or the last one with employees[-1] (in this case they are the same).

If you need a copy, you can call .copy() on the result:

second_employee = employees[1]
copied_details = second_employee.copy()

CodePudding user response:

Quick Answer:

employees is a list of dictionaries so you can just directly index the list to get Michell:

newDict = employees[1]

More Detailed Answer:

Firstly, here is how you create a key-value pair in a dictionary:

dct = {}
dct['color'] = 'blue' # dct = {'color':'blue'}

Knowing this, all you would need to copy a dictionary is the keys and values. You can use the .keys(),.values(), and .items() methods of dictionaries to do this.

dct.keys() # returns a list of all the keys -> ['color']
dct.values() # returns a list of all the values -> ['blue']
dct.items() # return a list of all the pairs as tuples -> [('color','blue')]

There are other options to copy as another user has mentioned however I strongly suggest you get used to work with the 3 methods listed above. If you haven't already, make sure you are really comfortable with lists before you jump into dictionaries and combined structures. You already seem to know how to work loops so hopefully this is helpful enough, good luck!

  • Related