OK this is a Python question:
We a have a dictionary:
my_dict = {
('John', 'Cell3', 5): 0,
('Mike', 'Cell2', 6): 1,
('Peter', 'Cell1', 6): 0,
('John', 'Cell1', 4): 5,
('Mike', 'Cell2', 1): 4,
('Peter', 'Cell1', 8): 9
}
How do you make another dictionary which has only the key/value pair which has the name "Peter" in it?
Does it help if you turn this dictionary to a list of tuples of tuples, by
tupled = my_dict.items()
and then turn it back to a dictionary again?
How do you solve this with list comprehension?
Thanks in advance!
items() , in dictionary iterates over all the keys and helps us to access the key-value pair one after the another in the loop and is also a good method to access dictionary keys with value.
Method 2: Extract specific keys from the dictionary using dict() The dict() function can be used to perform this task by converting the logic performed using list comprehension into a dictionary.
Try this, using the dictionary comprehensions available in Python 2.7 or newer:
{ k:v for k,v in my_dict.items() if 'Peter' in k }
Alternatively, if we're certain that the name will always be in the first position, we can do this, which is a bit faster:
{ k:v for k,v in my_dict.items() if k[0] == 'Peter' }
If you're using an older version of Python, we can get an equivalent result using generator expressions and the right parameters for the dict()
constructor:
dict((k,v) for k,v in my_dict.items() if k[0] == 'Peter')
Anyway, the result is as expected:
=> {('Peter', 'Cell1', 8): 8, ('Peter', 'Cell1', 6): 0}
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