Python Cookbook 1.17 从字典中提取子集

利用字典推导式可以轻松解决。

有如下字典:

prices = {'a': 3, 'b': 5, 'c': 1, 'd': 9, 'e': 3}

我们要将其中 value 值大于 4 的选出来,可以如此实现:

{key:value for key, value in prices.items() if value > 3}
Out[69]: {'b': 5, 'd': 9}

后面的 if 的条件可以自己变化,比如:

target = {'a', 'c', 'f'}

{key:value for key, value in prices.items() if key in target}
Out[71]: {'a': 3, 'c': 1}

你可能感兴趣的:(python,Python,Cookbook)