Set Operations on Dicts

Ian Kelly ian.g.kelly at gmail.com
Mon Feb 8 11:12:45 EST 2016


On Mon, Feb 8, 2016 at 5:47 AM, Grobu <snailcoder at retrosite.invalid> wrote:
> You can use dictionary comprehension :
>
> Say :
> dict1 = {'a': 123, 'b': 456}
> set1 = {'a'}
>
> intersection :
>>>> { key:dict1[key] for key in dict1 if key in set1 }
> {'a': 123}
>
> difference :
>>>> { key:dict1[key] for key in dict1 if not key in set1 }
> {'b': 456}

dict does already expose set-like views. How about:

{k: d[k] for k in d.keys() & s}  # d & s
{k: d[k] for k in d.keys() - s}  # d - s


More information about the Python-list mailing list