kh_si0567 kh_si0567 - 2 months ago 7
Python Question

Extracting a data from dictionary in python

list1 = ["a","c","d"]
dict1 = {"a":9, "b":2, "c":5, "d":9, "e":6, "f":7 }


I want to get only list1's word from dict1.

The following is the result I want to get.

{"a":9, "c":5, "d":9}


What am I supposed to do?

Answer

You can use a dictionary comprehension to do this:

>>> list1 = ["a","c","d"]
>>> dict1 = {"a":9, "b":2, "c":5, "d":9, "e":6, "f":7 }
>>> {k: dict1[k] for k in list1}
{'c': 5, 'd': 9, 'a': 9}

This works as long as the dictionary keys contains all the items in list1, otherwise you may use a filter, to test for items in list1 that are not in the dictionary:

>>> {k: dict1[k] for k in list1 if k in dict1}
{'c': 5, 'd': 9, 'a': 9}