python2 中實現字典公共鍵提取
阿新 • • 發佈:2018-12-16
# 建立相同公共鍵字典 from random import randint,sample sample('abcdefg',randint(3,6)) s1 = {k:randint(1,4) for k in sample('abcdefg',randint(3,6)) } s2 = {k:randint(1,4) for k in sample('abcdefg',randint(3,6)) } s3 = {k:randint(1,4) for k in sample('abcdefg',randint(3,6)) } # 提取字典中公共鍵第一種方法: for k in s1: res = [] if k in s2 and k in s3: res.append(k) print(res) # 第二種方法:使用字典的viewkeys()方法得到一個字典keys的集合 s1.viewkeys() & s2.viewkeys() & s3.viewkeys() # 第三種方法:(1)使使用map函式得到所有字典的keys的集合 map(dict.viewkeys,[s1,s2,s3]) # (2)使用reduce函式,取所有字典keys的集合的交集 reduce(lambda a,b :a & b,map(dict.viewkeys,[s1,s2,s3]))