利用集合(set)的交集操作

1.使用字典的keys()方法,得到一个字典keys的集合
2.使用map函数,得到每个字典keys的集合
3.使用reduce函数,去所有字典的keys集合的交集

  1. from random import randint, sample
  2. from functools import reduce
  3. d1 = {k: randint(1, 4) for k in sample('abcdefgh', randint(3, 6))}
  4. d2 = {k: randint(1, 4) for k in sample('abcdefgh', randint(3, 6))}
  5. d3 = {k: randint(1, 4) for k in sample('abcdefgh', randint(3, 6))}
  6. d = [d1, d2, d3]
  7. print(reduce(lambda a, b: a & b, map(dict.keys, d)))