从字典列表中创建一组键

时间:2014-08-18 23:19:31

标签: python list dictionary set

我想从列表中创建一个条目,其条目是字典。 知道如何用简短的Python语法做到这一点吗?

自:

[{"a":45,"b":2,"c":"house"},{"a":36,"d":67,"e":"car"}]

要:

{"a","b","c","d","e"}

谢谢!

3 个答案:

答案 0 :(得分:3)

试试这个:

lst = [ {"a":45, "b":2, "c":"house"}, {"a":36, "d":67, "e":"car"} ]
{ k for d in lst for k in d }
=> set(['a', 'c', 'b', 'e', 'd'])

请注意,我在问题的正文中返回了一个无序的,但是您正在使用这些键打印列表,但是问题的标题表明需要一组密钥。

答案 1 :(得分:2)

简短的语法是:

>>> dicts = [{"a":45,"b":2,"c":"house"},{"a":36,"d":67,"e":"car"}]
>>> set().union(*dicts)
set(['a', 'c', 'b', 'e', 'd'])

答案 2 :(得分:0)

mySet = set([])
for l in dictList:
    mySet = mySet.union(set(list(l)))