所以说我有我的字典
In [80]: dict_of_lists
Out[80]:
{'Marxes': ['Groucho', 'Chico', 'Harpo'],
'Pythons': ['Chapman', 'Cleese', 'Gilliam'],
'Stooges': ['Larry', 'Curly', 'Moe']}
我意识到以后我会希望将值视为集合。如何将字典从值(列表)转换为值(集)结构?
这已经尝试过了。
In [84]: new_dict = [set(dict_of_lists.values()) for values in dict_of_lists.keys()]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-84-f49792cd81ac> in <module>()
----> 1 new_dict = [set(dict_of_lists.values()) for values in dict_of_lists.keys()]
<ipython-input-84-f49792cd81ac> in <listcomp>(.0)
----> 1 new_dict = [set(dict_of_lists.values()) for values in dict_of_lists.keys()]
TypeError: unhashable type: 'list'
这个非常难看的努力。
In [83]: for list(dict_of_lists.keys()) in dict_of_lists:
....: set list(dict
dict dict_of_lists
....: set(list(dict_of_lists.values()))
....:
File "<ipython-input-83-08e0645abb2f>", line 1
for list(dict_of_lists.keys()) in dict_of_lists:
^
SyntaxError: can't assign to function call
答案 0 :(得分:3)
您只需要:
for k, v in d.items():
d[k] = set(v)
详细说明您的尝试无效的原因:
new_dict = [set(dict_of_lists.values()) for values in dict_of_lists.keys()]
在这一行中,您是:
.keys()
,因为它是字典上迭代的默认值); values
(令人困惑,如果不一定是终端); 然后:
for list(dict_of_lists.keys()) in dict_of_lists:
现在你隐式迭代密钥,这很好,但是然后尝试将每个密钥分配给list
的调用结果,再次显式调用keys
;实际上,这一行是:
['Marxes', 'Pythons', 'Stooges'] = 'Marxes'
没有任何意义。
答案 1 :(得分:1)
使用词典理解:
>>> x
{'Pythons': ['Chapman', 'Cleese', 'Gilliam'], 'Marxes': ['Groucho', 'Chico', 'Harpo'], 'Stooges': ['Larry', 'Curly', 'Moe']}
>>> y = {k:set(v) for k,v in x.items()}
>>> y
{'Pythons': {'Gilliam', 'Chapman', 'Cleese'}, 'Marxes': {'Groucho', 'Chico', 'Harpo'}, 'Stooges': {'Curly', 'Moe', 'Larry'}}
答案 2 :(得分:1)
dict_of_sets = {k:set(v) for k,v in dict_of_lists.items()}
这给出了:
{'Stooges': {'Curly', 'Larry', 'Moe'}, 'Pythons': {'Cleese', 'Chapman', 'Gilliam'}, 'Marxes': {'Groucho', 'Chico', 'Harpo'}}