简体   繁体   English

Python将列表的字典转换为集合的字典?

[英]Python convert dict of lists to dict of sets?

I have: 我有:

myDict = {'a': [1,2,3], 'b':[4,5,6], 'c':[7,8,9]}

I want: 我想要:

myDict = {'a': set([1,2,3]), 'b':set([4,5,6]), 'c':set([7,8,9])}

Is there a one-liner I can use to do this rather than looping through it and converting the type of the values? 我可以使用单行代码来执行此操作,而不是遍历它并转换值的类型吗?

You'll have to loop anyway: 无论如何,您都必须循环:

{key: set(value) for key, value in yourData.items()}

If you're using Python 3.6+, you can also do this: 如果您使用的是Python 3.6+,则还可以执行以下操作:

dict(zip(myDict.keys(), map(set, myDict.values())))

You can't do it without looping anyway, but you can have the looping done in one line, with the following code: 没有循环就无法做到这一点,但是可以使用以下代码在一行中完成循环:

myDict = {k:set(v) for k, v in myDict.items()}

This is basically traversing each item in your dictionary and converting the lists to sets and combining the key(str):value(set) pairs to a new dictionary and assigning it back to myDict variable. 这基本上是遍历字典中的每个项目,并将列表转换为集合,然后将key(str):value(set)对组合为新字典,并将其分配回myDict变量。

You can use comprehension for it: 您可以对其进行理解:

Basically, loop through the key-value pairs and create set out of each value for the corresponding key. 基本上,循环遍历键值对,并从每个值中为对应的键创建set。

>>> myDict = {'a': [1,2,3], 'b':[4,5,6], 'c':[7,8,9]}
>>> myDict = {k: set(v) for k, v in myDict.items()}
>>> myDict
{'a': {1, 2, 3}, 'b': {4, 5, 6}, 'c': {8, 9, 7}}

This can be done with map by mapping the values to type set 可以使用map通过将值映射到类型set

myDict = dict(map(lambda x: (x[0], set(x[1])), myDict.items()))

Or with either version of dictionary comprehension as well 或同时使用任一版本的词典理解

myDict = {k: set(v) for k, v in myDict.items()}
myDict = {k: set(myDict[k]) for k in myDict}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM