【问题标题】:Python 3 convert dictonary values to a setPython3 将字典值转换为集合
【发布时间】:2014-10-11 11:29:17
【问题描述】:

所以说我有我的字典

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

【问题讨论】:

  • 请显示您希望看到什么样的结果集
  • 您实际上是在创建一个值列表作为集合,而不是字典。这是你想要的吗?

标签: python python-3.x dictionary


【解决方案1】:

你只需要:

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'

这没有任何意义。

【讨论】:

    【解决方案2】:

    使用字典理解:

    >>> 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'}}
    

    【讨论】:

      【解决方案3】:
      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'}}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-03
        • 2015-10-24
        • 2019-09-13
        • 1970-01-01
        • 2011-08-02
        • 2022-01-16
        相关资源
        最近更新 更多