Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting key/value pair from dictionary

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!

like image 538
Kristof Pal Avatar asked Jun 12 '13 21:06

Kristof Pal


People also ask

How do you find the key-value pair in the dictionary?

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.

How do I extract all the values of specific keys from a list of dictionaries?

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.


1 Answers

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}
like image 188
Óscar López Avatar answered Sep 30 '22 11:09

Óscar López