【问题标题】:Group key-value pairs and get count using Counter in python 3在 python 3 中使用 Counter 对键值对进行分组并获取计数
【发布时间】:2021-07-31 13:12:32
【问题描述】:

我有一个这样的字典列表:

res = [{"isBlack": "yes"} , {"isWhite": "no"} , {"isRed": "yes"} , {"isWhite": "yes"} , {"isRed": "no"} , {"isBlack": "yes"}]

我需要按键值对对 res 进行分组,并使用 Counter 获取它们的计数,如下所示:

Counter({"isBlack:yes": 2 , "isWhite:no": 1, "isWhite:yes": 1 , "isRed:no": 1 , "isRed:yes": 1}) 

我试过这个: count = Counter(res) ,但出现如下错误:

TypeError: unhashable type: 'dict'

还有什么我可以尝试的吗?

【问题讨论】:

    标签: python python-3.x list dictionary counter


    【解决方案1】:

    您可以使用dict.popitem方法先获取每个sub-dict中的item元组,然后将元组连接成冒号分隔的字符串传递给Counter

    Counter(':'.join(d.popitem()) for d in res)
    

    这会返回:

    Counter({'isBlack:yes': 2, 'isWhite:no': 1, 'isRed:yes': 1, 'isWhite:yes': 1, 'isRed:no': 1})
    

    或者,不使用冒号分隔的字符串作为键,将dict.items() 方法生成的键值元组作为键会更惯用:

    Counter(i for d in res for i in d.items())
    

    这会返回:

    Counter({('isBlack', 'yes'): 2, ('isWhite', 'no'): 1, ('isRed', 'yes'): 1, ('isWhite', 'yes'): 1, ('isRed', 'no'): 1})
    

    【讨论】:

      【解决方案2】:

      您只需要在生成器表达式中进行一些预处理即可将字典转换为字符串。

      print(Counter(f"{next(iter(d))}:{d[next(iter(d))]}" for d in res))
      

      next(iter(d)) 是获取字典中的第一个键(恰好是这里唯一的一个)。

      【讨论】:

      • 谢谢@SuperStormer...您的解决方案非常完美。早先的错误是我这边的错误,因为我输入了错误的输入。
      猜你喜欢
      • 2017-09-25
      • 2013-08-13
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      相关资源
      最近更新 更多