Python:来自多个字典的联合键? [英] python: union keys from multiple dictionary?

查看:167
本文介绍了Python:来自多个字典的联合键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有5个字典,我想要它们的键的并集.

I have 5 dictionaries and I want a union of their keys.

alldict =  [dict1, dict2, dict3, dict4, dict5]

我尝试过

allkey = reduce(lambda x, y: set(x.keys()).union(y.keys()), alldict)

但这给了我一个错误

AttributeError: 'set' object has no attribute 'keys'

我做错了吗?我使用普通的forloop,但我不知道为什么上面的代码不起作用.

Am I doing it wrong ? I using normal forloop but I wonder why the above code didn't work.

推荐答案

您的解决方案适用于列表中的前两个元素,但随后dict1dict2被简化为一个集合,并将该集合放入您的lambda作为x.因此,现在x不再具有方法keys().

Your solution works for the first two elements in the list, but then dict1 and dict2 got reduced into a set and that set is put into your lambda as the x. So now x does not have the method keys() anymore.

解决方案是从一开始就通过用空集(恰好是并集的中性元素)初始化归约使x成为一个集.

The solution is to make x be a set from the very beginning by initializing the reduction with an empty set (which happens to be the neutral element of the union).

尝试使用初始化程序:

allkey = reduce(lambda x, y: x.union(y.keys()), alldict, set())

没有任何lambda的替代方法是:

An alternative without any lambdas would be:

allkey = reduce(set.union, map(set, map(dict.keys, alldict)))

这篇关于Python:来自多个字典的联合键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆