码迷,mamicode.com
首页 > 其他好文 > 详细

从多个字典中提取相同的key

时间:2017-06-08 10:30:15      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:ict   highlight   pen   method   提取   取出   app   logs   generate   

有时有多个字典,需要从中提取出这些字典中共有的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),就可能超出边界。

从多个字典中提取相同的key

标签:ict   highlight   pen   method   提取   取出   app   logs   generate   

原文地址:http://www.cnblogs.com/Andy963/p/6958844.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!