有时有多个字典,需要从中提取出这些字典中共有的key
#!/usr/bin/env python #coding:utf-8 #@Author:Andy from random import randint, sample # select the same key from different dict print("Generate 3 dif dict:") d1 = {k:randint(1, 10) for k in sample(["小王","小段","小李","小周","小小"],randint(1,5))} d2 = {k:randint(1, 10) for k in sample(["小王","小段","小李","小周","小小"],randint(1,5))} d3 = {k:randint(1, 10) for k in sample(["小王","小段","小李","小周","小小"],randint(1,5))} for _ in (d1, d2, d3): print(_) print("method 1:") res = [] for _ in d1: if _ in d2 and _ in d3: res.append(_) print(res)
但是注意,如果出现 :sample larger than population的错误提示:如下图:
那是因为,randint(x,y)是左右都包含的,如果元素就5个,却用了randin(1,6),就可能超出边界。