1、取字典中的公共key:
from random import randint,sample
//sample('abcdefg', 3) 从列表中随机取出3个对象
s1 = { x: randint(1,4) for x in sample('abcdefg', randint(3,6))}
//s1 = {'c': 1, 'b': 1, 'g': 3, 'f': 2}
s2 = { x: randint(1,4) for x in sample('abcdefg', randint(3,6))}
//s2 = {'c': 2, 'b': 4, 'e': 3, 'd': 1, 'g': 1, 'f': 2}
s3 = { x: randint(1,4) for x in sample('abcdefg', randint(3,6))}
// s3 = {'a': 3, 'c': 3, 'b': 4, 'e': 2, 'g': 3}
res = []
方法一:
for k in s1:
if k in s2 and k in s3:
res.append(k)
方法二:利用set的交集操作:
//s2.viewkeys() 返回所有字典的key的集合
//dict_keys(['c', 'b', 'e', 'd', 'g', 'f'])
res = &s2.viewke