Python3 快速找到多个字典的公共键-新乡seo|网站优化,网站建设—昊天博客

快速找字典中的公共键

第一步:升级随机的字典


In [24]: from random import randint,sample

In [25]: sample('abcdefg',3)
# sample 取样
Out[25]: ['e', 'g', 'd']

In [26]: sample('abcdefg',randint(3, 6))
Out[26]: ['a', 'f', 'b', 'c']

In [27]: s1= {x:randint(1,4) for x in sample('abcdefg',randint(3, 6))}
# 字典生成器
In [28]: s1
Out[28]: {'b': 3, 'c': 1, 'd': 2, 'e': 3, 'f': 1, 'g': 1}

In [29]: s2= {x:randint(1,4) for x in sample('abcdefg',randint(3, 6))}

In [30]: s3= {x:randint(1,4) for x in sample('abcdefg',randint(3, 6))}

In [31]: s1
Out[31]: {'b': 3, 'c': 1, 'd': 2, 'e': 3, 'f': 1, 'g': 1}

In [32]: s2
Out[32]: {'a': 2, 'b': 2, 'c': 2, 'e': 3, 'f': 2, 'g': 2}

In [33]: s3
Out[33]: {'a': 3, 'b': 2, 'c': 4, 'e': 4, 'f': 3, 'g': 2}
生成带有公共键的表达式

数据已经产生了,下一步就是获取各个字典的键值
先看下python3 有没有直接可以使用的属性

In [45]: dir(s1)
Out[45]:
['__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'clear',
 'copy',
 'fromkeys',
 'get',
 'items',
 'keys',# 这个就是可以获取键的函数
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values']

所以接下来就很简单了,取下三个集合的交集 就可以了


In [44]: s1.keys()&s2.keys()&s3.keys()
Out[44]: {'b', 'c', 'e', 'f', 'g'}

还有一种麻烦的做法:

利用map函数和reduce,由于reducepython3 中已经移除了,需要从标准库中找

In [42]: from functools import reduce

"""
In [46]: map?
Init signature: map(self, /, *args, **kwargs)
Docstring:
map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
Type: type
"""
map(dict.keys, [s1,s2,s3])


<strong>对象然后转成列表</strong>


In [38]: list(map(dict.keys, [s1,s2,s3]))
Out[38]:
[dict_keys(['b', 'e', 'f', 'g', 'c', 'd']),
dict_keys(['f', 'g', 'a', 'e', 'b', 'c']),
dict_keys(['c', 'e', 'g', 'f', 'a', 'b'])]

In [42]: from functools import reduce

In [43]: reduce(lambda x,y:x&amp;y, list(map(dict.keys, [s1,s2,s3])))
Out[43]: {'b', 'c', 'e', 'f', 'g'}