简体   繁体   中英

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?

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM