通过特定键计算字典中的重复项

辛格斯·阿克玛托夫(Chyngyz Akmatov)

我有一个字典列表,我需要按特定键来计算重复项。例如:

[
   {'name': 'John', 'age': 10, 'country': 'USA', 'height': 185}, 
   {'name': 'John', 'age': 10, 'country': 'Canada', 'height': 185}, 
   {'name': 'Mark', 'age': 10, 'country': 'USA', 'height': 180},
   {'name': 'Mark', 'age': 10, 'country': 'Canada', 'height': 180},
   {'name': 'Doe', 'age': 15, 'country': 'Canada', 'height': 185}
]

如果指定“年龄”和“国家”,则应返回

[  
   {
      'age': 10,
      'country': 'USA',
      'count': 2 
   },
   {
      'age': 10,
      'country': 'Canada',
      'count': 2 
   },
   {
      'age': 15,
      'country': 'Canada',
      'count': 1
   }
]

或者,如果我要指定“名称”和“高度”:

[  
   {
      'name': 'John',
      'height': 185,
      'count': 2 
   },
   {
      'name': 'Mark',
      'height': 180,
      'count': 2 
   },
   {
      'name': 'Doe',
      'heigth': 185,
      'count': 1
   }
]

也许有一种方法可以通过Counter来实现?

塞扬迪普·杜塔(Sayandip Dutta)

您可以使用itertools.groupbysorted列表:

>>> data = [
   {'name': 'John', 'age': 10, 'country': 'USA', 'height': 185}, 
   {'name': 'John', 'age': 10, 'country': 'Canada', 'height': 185}, 
   {'name': 'Mark', 'age': 10, 'country': 'USA', 'height': 180},
   {'name': 'Mark', 'age': 10, 'country': 'Canada', 'height': 180},
   {'name': 'Doe', 'age': 15, 'country': 'Canada', 'height': 185}
]
>>> from itertools import groupby
>>> key = 'age', 'country'
>>> list_sorter = lambda x: tuple(x[k] for k in key)
>>> grouper = lambda x: tuple(x[k] for k in key)
>>> result = [
        {**dict(zip(key, k)), 'count': len([*g])} 
         for k, g in 
         groupby(sorted(data, key=list_sorter), grouper)
    ]
>>> result

[{'age': 10, 'country': 'Canada', 'count': 2},
 {'age': 10, 'country': 'USA', 'count': 2},
 {'age': 15, 'country': 'Canada', 'count': 1}]

>>> key = 'name', 'height'
>>> result = [
        {**dict(zip(key, k)), 'count': len([*g])} 
         for k, g in 
         groupby(sorted(data, key=list_sorter), grouper)
    ]

>>> result

[{'name': 'Doe', 'height': 185, 'count': 1},
 {'name': 'John', 'height': 185, 'count': 2},
 {'name': 'Mark', 'height': 180, 'count': 2}]

如果你使用pandas,你可以使用,pandas.DataFrame.groupbypandas.groupby.sizepandas.Series.to_framepandas.DataFrame.reset_index终于pandas.DataFrame.to_dictorient='records'

>>> import pandas as pd
>>> df = pd.DataFrame(data)
>>> df.groupby(list(key)).size().to_frame('count').reset_index().to_dict('records')

[{'name': 'Doe', 'height': 185, 'count': 1},
 {'name': 'John', 'height': 185, 'count': 2},
 {'name': 'Mark', 'height': 180, 'count': 2}]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章