从多个字典中提取相同的key
Posted 安迪_963
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从多个字典中提取相同的key相关的知识,希望对你有一定的参考价值。
有时有多个字典,需要从中提取出这些字典中共有的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的主要内容,如果未能解决你的问题,请参考以下文章
Python 如果两个字典key值相同,如何提取对应values组成新的字典
Ansible - 通过循环注册 GET 响应,多个相同的字典