簡體   English   中英

如何在字典列表中找到公用鍵並按值對它們進行排序?

[英]How to find common keys in a list of dicts and sort them by value?

我想創建一個finalDic,其中包含公用密鑰及其值的總和

myDic = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}, ...]

首先找到通用密鑰

commonkey = [{2:1, 3:1}, {2:3, 3:4}, {2:5, 3:6}]

然后求和並按其值排序

finalDic= {3:11, 2,9}

我已經嘗試過了,甚至沒有關閉我想要的東西

import collections

myDic = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}]

def commonKey(x):
    i=0
    allKeys = []
    while i<len(x):
        for key in x[0].keys():
            allKeys.append(key)
        i=i+1
    commonKeys = collections.Counter(allKeys)
    commonKeys = [i for i in commonKeys if commonKeys[i]>len(x)-1]
    return commonKeys

print commonKey(myDic)

謝謝

這是我的處理方式:

my_dict = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}]

# Finds the common keys
common_keys = set.intersection(*map(set, my_dict))

# Makes a new dict with only those keys and sums the values into another dict
summed_dict = {key: sum(d[key] for d in my_dict) for key in common_keys}

或者作為瘋狂的單線客:

{k: sum(d[k] for d in my_dict) for k in reduce(set.intersection, map(set, my_dict))}

只有一些指針:

  • 從每個目錄中獲取鍵,然后將它們轉換為set()並計算交集()或所有鍵集。 這將為您提供通用密鑰。
  • 現在迭代原始數據並匯總每個字典的匹配值很簡單

實施留給OP作為練習。

l = [{2:1, 3:1, 5:2}, {3:4, 6:4, 2:3}, {2:5, 3:6}]

new_dict = {}

def unique_key_value(a,b):
    return set(a).intersection(set(b))

def dict_sum(k, v):
    if k not in new_dict.keys():
        new_dict[k] = v
    else:
        new_dict[k] = new_dict[k] + v

for i in reduce(unique_key_value, l):
    for k in l:
        if i in k.keys():
            dict_sum(i, k[i])

print new_dict

希望這可以幫助。 :)

python 3.2

from collections import defaultdict
c=defaultdict(list)
for i in myDic:
     for m,n in i.items():
            c[m].append(n)
new_dic={i:sum(v) for i,v in c.items()if len(v)==len(myDic)}
print(new_dic)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM