In this Python Tutorial, we will see how to copy specific keys in Python Dictionary using some examples.
A Python dictionary contains data values in key: value pairs. But, we often want to see some particular elements(specific keys) from the Python dictionary rather than the whole dictionary.
For example:
example_dict = {
'AMC Rebel SST': 150.0,
'Ford Torino': 140.0,
'Ford Galaxie 500': 198.0,
'Chevrolet Impala': 220.0,
'Plymouth Fury iii': 215.0
}
The Python dictionary items are ordered, changeable, and do not allow duplicates. Dictionary items are presented in key: value pairs and can be referred to using the key name. So, we cannot use slicing to get the desired output as we do in the Python list.
To get that sorted elements in a dictionary in Python. We will use different methods to copy specific keys in the Python dictionary. They are:
- using Dictionary comprehension and keys() method.
- using the dict() method.
- using filter() and lambda method.
- using a for loop and a conditional statement.
- using get() method.
Copy specific keys in Python Dictionary
As we know, the elements of the Python dictionary are ordered and can access through the keys. The 5 methods to copy these Specific keys in the Python dictionary are explained below:
Method-1: Copying specific keys using dictionary comprehension and keys() method in Python
In this method, we are using the common method to copy some particular elements from a Python dictionary. We will use dictionary comprehension for the reconstruction using keys() to filter the required keys.
In the following code of Python, we have data in the form of a Python dictionary of a flower shop. i.e. the name of flowers as keys and quantity available in the shop as values for the Python dictionary.
As shopkeepers, we want to see the quantity available for some of the flowers in the shop.
flowers = {
'white orchids': 120,
'dahlias': 150,
'calla lilies': 220,
'sunflowers': 180,
'protea': 120,
'roses': 152,
'fuchsia': 165,
'tweedia': 220
}
# using dict. comprehension and keys() method
specific_flowers = {key: flowers[key] for key in flowers.keys()
& {'roses', 'calla lilies'}}
# printing Output
print('Quantity available:', specific_flowers)
The output of this block of code is:
Quantity available: {'calla lilies': 220, 'roses': 152}
We can see only the desired flower names and their quantity available in the shop came as the output. So, this way we can use dictionary comprehension with the keys() method to copy the specific keys in a Python dictionary.
Method-2: Copying specific keys using dict() method in Python
We have 2 different ways to use the dict() method in Python:
- Using the dict() method with for loop in Python
- Using the dict() method with the list() method and list slicing in Python
Method-2.1: Using the dict() method with for loop.
The dict() method is used to create a Python dictionary. Here, we choose the required keys of the dictionary while passing on the keys to the dict() function. Along with using a Python for loop.
In the example, we have all the employees’ names as keys and their email addresses as values stored in the form of the Python dictionary. Here, we have sorted some names to send the email to.
employee = {
'ashley': 'ashley@example.com',
'craig': 'craig@example.com',
'elizabeth': 'elizabeth@example.com',
'sam': 'sam@example.com',
'ian': 'ian@example.com',
'joey': 'joey@example.com'
}
sorted_employee = dict((key, employee[key]) for key in ['joey', 'craig', 'ian'] if key in employee)
print('Kindly send the E-mail to: \n', sorted_employee)
The output for the above block of code is :
Kindly send the E-mail to:
{'joey': 'joey@example.com', 'craig': 'craig@example.com', 'ian': 'ian@example.com'}
As we can easily use the dict() method with for loop to get only some data from the Python dictionary.
Method-2.2: Using the dict() method with the list() method and list slicing in Python.
As we know, the dict() method will create a dictionary in Python. The list() method will return a list in Python, and the list is ordered and changeable. We can refer to items of a list in Python using indexes. So, we can use list slicing in this process of copying specific keys in the Python dictionary.
In the example, we will see how we can get the first five elements of the Python dictionary. We have the names of the game as keys and the number of participants in the respective game as values stored in a dictionary.
Being an organizer we have decided to select the number of games to be played on day 01 of the event. So generally, we have selected the first five data stored in the dictionary.
Games = {
'Archery': 6,
'Badminton': 2,
'Boxing': 4,
'Tennis': 4,
'Judo': 2,
'Short put': 5,
'Discuss': 9,
'weight lifting': 5
}
first_five_games = dict(list(Games.items())[:5])
print('The Games should we played on day01:\n', first_five_games)
The output is:
The Games should we played on day01:
{'Archery': 6, 'Badminton': 2, 'Boxing': 4, 'Tennis': 4, 'Judo': 2}
As we can see, we got the first five pieces of data stored in the Python dictionary.
Method-3: Copying specific keys using the filter() and lambda method in Python.
The Python filter() method will filter the given iterable(dictionary) with the help of a function that filters out specific elements in the sequence to be true or not based on the condition that we provide.
The lambda is a function in Python, which can take any number of arguments in one expression.
In this example, we have people’s names as keys who came to the hospital to donate blood and their blood group and phone number as values stored in the form of a Python dictionary in the hospital.
Some types of blood were more required in the hospital for the treatment of patients. As this was urgent the hospital authority decided to call out previous donors to donate some more units of blood.
We have to separate the donors required to be called. So first, we will create a list with the names of people to be called out and then we filter the data in
donor ={
'Betty': {'O+', 548489956},
'John': {'O+', 519592955},
'Emily': {'AB+', 789989885},
'Ashley': {'B-', 454556123},
'Dave': 'O-', 4545453321},
'David': 'A+', 322557890},
'Sam': 'B-', 979898120},
'Monica': 'O+', 789950012}
}
Required_people = ['John', 'Monica', 'Ashley', 'Sam']
final_dict = dict(filter(lambda item: item[0] in Required_people, donor.items()))
print('people required in the hospital are: \n', final_dict)
The output is:
people required in the hospital are:
{'John': {519592955, 'O+'}, 'Ashley': {454556123, 'B-'}, 'Sam': {979898120, 'B-'}, 'Monica': {789950012, 'O+'}}
This way we got the specific donor required to be called out from a data of Python dictionary.
Method-4: Copying specific keys using a for loop and a conditional statement in a Python dictionary.
In this method, first, we will create a list with the names of the specific keys. Then, we will have an empty dictionary to store the result. Lastly, we will loop over the initial dictionary with the help of a conditional statement and will store the true conditions in our empty dictionary as a result.
In the example, we have a list of teams from Major League Baseball in the USA and their cities respectively stored in the form of a Python dictionary. We have to sort out the team’s details going to play the final.
MLB_team = {
'Rockies': 'Colorado',
'Red Sox': 'Boston',
'Twins': 'Minnesota',
'Brewers': 'Milwaukee',
'Mariners': 'Seattle'
}
finalist = ['Twins', 'Mariners']
finalist_dict = {}
for key, value in MLB_team.items():
if key in finalist:
finalist_dict[key] = value
print('finalist are: \n', finalist_dict)
The output of the code is:
finalist are:
{'Twins': 'Minnesota', 'Mariners': 'Seattle'}
This way we can get the specific data required from the Python dictionary using a for loop and a conditional statement.
Method-5: Copying specific keys using the get() method in Python.
The get() method in Python returns the values of a specific key. In this code, we have the details of the president of the USA and, we want to get whether he has pets or not.
president = {
'fname': 'Barack',
'lname': 'Obama',
'age': 61,
'spouse': 'Michelle',
'children': ['Malia Ann', 'Sasha'],
'pets': {'dog': ['Bo', 'Sunny']}
}
Data_required = {key:president.get(key) for key in ('fname', 'lname', 'pets')}
print('The president name and their pets are: \n', Data_required)
The output is:
The president name and their pets are:
{'fname': 'Barack', 'lname': 'Obama', 'pets': {'dog': ['Bo', 'Sunny']}}
This way we can get the specific keys copied into another dictionary using the get() method in the dictionary in Python.
Conclusion:
After reading this, we came to know that, dictionaries in Python are ordered and can only be referred to by keys. So, to copy specific keys in a Python dictionary we have 5 methods.
You may like to read:
- How to update duplicate keys in Python Dictionary
- How to remove duplicate values from a Python Dictionary
- Remove empty keys in dictionary Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.