Everfighting
5/18/2017 - 2:28 PM

如何快速找到多个字典中出现的公共键

如何快速找到多个字典中出现的公共键

from random import randint,sample
s1 = {x: randint(1,4) for x in sample('abcdefg',ranint(3,6))}
s2 = {x: randint(1,4) for x in sample('abcdefg',ranint(3,6))}
s3 = {x: randint(1,4) for x in sample('abcdefg',ranint(3,6))}

# 法一
res = []
for k in s1:
  if k in s2 and s3:
    res.append(k)

# 法二
s1.viewkeys()&s2.viewkeys()&s3.viewkeys()

## 法二进阶版
map(dict.viewkeys,[s1,s2,s3])
>>> [dict_keys(['a','b','e','f']),
    dict_keys(['c','e','g','g']),
     dict_keys(['b','e','d','g','f'])]
reduce(lambda a,b:a &b,map(dict.viewkeys,[s1,s2,s3]))