【问题标题】:Turning dictionary values into sets?将字典值转换为集合?
【发布时间】:2018-04-30 22:28:36
【问题描述】:

如何将dictionary1 变成dictionary2?基本上,我想将所有字典值转换为集合,以便字典值中没有重复项。

我试着做dictionary2 = set(dictionary1.values()),但这个功能没有给我我想要的东西。

dictionary1 = {
    'cat': ['frog', 'frog'] ,
    'dog': ['deer', 'deer', 'deer', 'goat'],
    'bat': ['apes,' 'mice', 'mice'] }

dictionary2 = {
    'cat': ['frog'] ,
    'dog': ['deer', 'goat'],
    'bat': ['apes,' 'mice'] }

【问题讨论】:

  • 这些不是集合,而是具有独特元素的列表。
  • 迭代dictionary1.items()的键值对,并用key:set(value)对构造一个新的字典。
  • a_set = set(dictionary.values())

标签: python dictionary set


【解决方案1】:
dictionary1 = {'cat': ['frog', 'frog'] , 'dog': ['deer', 'deer', 'deer', 'goat'], 'bat': ['apes,' 'mice', 'mice'] }
dict2={i:list(set(dictionary1[i])) for i in dictionary1}

【讨论】:

    【解决方案2】:

    调用dictionary2 = set(dictionary1.values()) 的问题在于dictionary1.values() 只是返回dictionary1 中每个值的列表。这些值中的每一个本身都是一个列表(例如,['frog', 'frog'].values() 列表的一个元素)。在多维列表上调用set()(这就是这里发生的情况)导致TypeError: unhashable type: 'list',因为set() 只接受不可变(可散列)对象的列表,但列表是可变的。请参阅this question 了解更多信息。

    除此之外,在dictionary1.values() 上调用set() 实际上只会减少值列表,因此不会重复动物列表。换句话说,set([('mouse', 'mouse'), ('mouse', 'mouse')]) 的结果是 {('mouse', 'mouse')} 而不是 {('mouse'), ('mouse')},我相信它更接近您正在寻找的东西。 (注意:这里使用元组,因为它们是不可变的)

    您想要做的是在dictionary1.values() 中的每个 值上调用set()(然后使用list() 转换回列表)并在新字典中执行此操作。这可以通过字典解析来完成(类似于更常见的列表解析)。

    这可以通过以下方式完成:

    dictionary1 = {'cat': ['frog', 'frog'] , 'dog': ['deer', 'deer', 'deer', 'goat'], 'bat': ['apes', 'mice', 'mice'] }
    dictionary2 = {key: list(set(value)) for key, value in dictionary1.items()}
    

    以上代码结果:

    dictionary1 #=> {'cat': ['frog', 'frog'] , 'dog': ['deer', 'deer', 'deer', 'goat'], 'bat': ['apes', 'mice', 'mice'] }
    dictionary2 #=> {'cat': ['frog'], 'dog': ['goat', 'deer'], 'bat': ['apes', 'mice']}
    

    根据需要。

    【讨论】:

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