开发者

How to filter a dict to contain only keys in a given list? [duplicate]

This question already has answers here: Filter dict to contain only certain keys? (23 answers) Closed 7 years ago.

Both very new to Python and stackoverflow. Thank you for your patience, and your help.

I wou开发者_如何学Pythonld like to filter a dict according to the content of a list like this:

d={'d1':1, 'd2':2, 'd3':3}

f = ['d1', 'd3']

r = {items of d where the key is in f}

Is this absurd? If not, what would be the right syntax?

Thank you for your help.

Vincent


Assuming you want to create a new dictionary (for whatever reason):

d = {'d1':1, 'd2':2, 'd3':3}
keys = ['d1', 'd3']

filtered_d = dict((k, d[k]) for k in keys if k in d)
# or: filtered_d = dict((k, d[k]) for k in keys)
# if every key in the list exists in the dictionary


You can iterate over the list with a list comprehension and look up the keys in the dictionary, e.g.

aa = [d[k] for k in f]

Here's an example of it working.

>>> d = {'k1': 1, 'k2': 2, 'k3' :3}
>>> f = ['k1', 'k2']
>>> aa = [d[k] for k in f]
>>> aa
[1, 2]

If you want to reconstruct a dictionary from the result, you can capture the keys as well in a list of tuples and convert to a dict, e.g.

aa = dict ([(k, d[k]) for k in f])

More recent versions of Python (specifically 2.7, 3) have a feature called a dict comprehension, which will do it all in one hit. Discussed in more depth here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜