【问题标题】:How to Find Common Keys in an Array of Dictionaries in Python如何在 Python 中查找字典数组中的公共键
【发布时间】:2020-12-05 10:01:45
【问题描述】:

给定一个字典数组:[{'key1': 'valueA', 'key2': 'valueB'}, {'key1': 'valueC', 'key3': 'valueD'}, {}, . ..]

您将如何找到字典中最常用的键并对它们进行排名?

在这个例子中,“key1”的键出现了两次,所以这将被排在第 1 位。然后如果“key2”以下一个常见频率出现,这将被排在第 2 位,依此类推。

【问题讨论】:

  • 到目前为止你为实现这个动机做了什么?
  • 要求最常见的键意味着确定一个阈值 s,使得:如果键 k 出现超过 s 次,则 k 是常见的。从您写的内容来看,您似乎只想根据频率对键进行排序,因为您没有提供“最常用键”的任何定义。
  • 我注意到有人投了反对票,所以我担心你会被击落,但不要个人认为。他们正在寻找一些努力的迹象。这可能可以简化为在列表列表中查找公共元素(其中每个字典的.keys() 是子列表)。这个问题在这里有答案:stackoverflow.com/questions/53515649/…

标签: python


【解决方案1】:

使用这个:

keys = dict()
# d is your dictionary
for i in d:
    for k, v in i.items():
        if k in keys:
            keys[k] += 1
        else:
            keys[k] = 1
max = 0
max_key = ''
for k, v in keys.items():
    if v > max:
        max = v
        max_key = k
print(max, max_key)

【讨论】:

    【解决方案2】:

    您可以使用pandas 来表示parse the dict,然后使用describe it to get stats

    import pandas as pd
    
    lod = [{'points': 50, 'time': '5:00', 'year': 2010}, 
    {'points': 25, 'time': '6:00', 'month': "february"}, 
    {'points':90, 'time': '9:00', 'month': 'january'}, 
    {'points_h1':20, 'month': 'june'}]
    
    df = pd.DataFrame(lod)
    
    print(df.describe(include=['float', 'object']))
    
    '''
               points  time    year    month  points_h1
    count    3.000000     3     1.0        3        1.0
    unique        NaN     3     NaN        3        NaN
    top           NaN  9:00     NaN  january        NaN
    freq          NaN     1     NaN        1        NaN
    mean    55.000000   NaN  2010.0      NaN       20.0
    std     32.787193   NaN     NaN      NaN        NaN
    min     25.000000   NaN  2010.0      NaN       20.0
    25%     37.500000   NaN  2010.0      NaN       20.0
    50%     50.000000   NaN  2010.0      NaN       20.0
    75%     70.000000   NaN  2010.0      NaN       20.0
    max     90.000000   NaN  2010.0      NaN       20.0
    '''
    

    但是请注意,这不适用于嵌套字典!你需要安装pandaspip

    【讨论】:

      【解决方案3】:

      这是你的答案

      from collections import Counter
      d=[{'key1': 'valueA', 'key2': 'valueB'}, {'key1': 'valueC', 'key3': 'valueD'}, {'key1': 'valueC'}]
      keys=[]
      for i in d:
          for j in i.keys():
              keys.append(j)
              
      Counter(keys)
      

      输出

      Counter({'key1': 3, 'key2': 1, 'key3': 1})
      

      【讨论】:

        【解决方案4】:

        您可以使用Counter 来计算:

        import collections
        
        def count(array):
            counter = collections.Counter()
            for dict in array:
                counter.update(dict.keys())
            return counter
        
        print(count([{'a': 1}, {'a': 2}])) # Counter({'a': 2})
        print(count([{'f': 2}, {'f': '2'}, {'b': 10}])) # Counter({'f': 2, 'b': 1})
        

        【讨论】:

          【解决方案5】:

          使用pandas 的另一个不错的解决方案是转换数据帧中的字典,合并它们,然后使用value_counts。这是一个小例子

          import pandas as pd
          
          d1 = {'key1': '1', 'key2': '2'}
          d2 = {'key1': '1', 'key3': '3'}
          
          df1 = pd.DataFrame.from_dict(d1.items())
          df2 = pd.DataFrame.from_dict(d2.items())
          
          frames = [df1, df2]
          result = pd.concat(frames)
          print(result[0].value_counts())
          

          打印出来的

          key1    2
          key2    1
          key3    1
          Name: 0, dtype: int64
          

          【讨论】:

            【解决方案6】:
            # Extract the keys in a flat list
            keys = [k for k, v in i.items for i in data]
            
            # Sort and group
            from itertools import sorted, groupby
            s = sorted(keys)
            g = groupby(s)
            

            【讨论】:

            • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
            【解决方案7】:

            使用collections.Counter的另一种方法:

            from collections import Counter
            d=[{'key1': 'valueA', 'key2': 'valueB'}, {'key1': 'valueC', 'key3': 'valueD'}, {} ]
            c = Counter(key for t in d for key in t.keys())
            

            输出:

            Counter({'key1': 2, 'key2': 1, 'key3': 1}) 
            

            【讨论】:

              【解决方案8】:

              有很多方法可以做到这一点,我认为最干净的方法之一是使用 Counter 类,但我会采用以下方式:

              my_dicts = [{"hello": 2},{"hello1": 3, "hello": 5},{"hello2": 5, "hello": 7, "hello1": 4}]
              
              
              merged = {}
              for d in my_dicts:
                for k in d.keys():
                  if k in merged:
                    merged[k] += 1
                  else:
                    merged[k] = 1
              results = {k: v for k, v in sorted(merged.items(), key=lambda item: item[1], reverse = True)}
              
              

              变量results 最终包含按降序排列的已排序项目的字典,如下所示:

              输出:

              {'hello': 3, 'hello1': 2, 'hello2': 1}
              

              【讨论】:

                【解决方案9】:

                试试这个;

                代码语法

                dicts =[{'key1': 'valueA', 'key2': 'valueB'}, {'key1': 'valueC', 'key3': 'valueD'}]
                
                lis = [list(dicts[i].keys()) for i in range(len(dicts))]
                x = sorted([j for i in lis for j in i])
                print(x)
                for i, each in enumerate(x):
                    if x[i-1] == x[i]:
                        continue
                    else:
                        indey = x.count(x[x.index(each)])
                        print(f"{each} = {indey}")
                

                输出

                ['key1', 'key1', 'key2', 'key3']
                key1 = 2
                key2 = 1
                key3 = 1
                
                [Program finished]
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2012-04-12
                  • 2023-01-26
                  • 1970-01-01
                  • 2023-01-12
                  • 2013-10-04
                  • 1970-01-01
                  • 1970-01-01
                  • 2015-08-05
                  相关资源
                  最近更新 更多