2016-12-16 21 views
-2

ich einige haben ...Haben Sie Probleme mit Python

[{"countryname": "Republic of Tunisia", "project_name": "TN: DTF Social Protection Reforms Support", "lendprojectcost": 5700000}, 
{"countryname": "Republic of Tunisia", "project_name": "Tunisia: Ecotourism and Conservation of Desert Biodiversity", "lendprojectcost": 9050000}, 
{"countryname": "Republic of Tunisia", "project_name": "Tunisia - Communications for policy reforms", "lendprojectcost": 600000}, 
{"countryname": "Republic of Tunisia", "project_name": "Tunisia - Governance, Opportunities and Jobs DPL", "lendprojectcost": 500000000}] 

Ich möchte:

[{"countryname": "Republic of Tunisia", "project_name":all projects, "lendprojectcost":sum(..) }] 

, wie kann ich dies tun? Ich habe Python/Flask/MongoDB verwendet.

+5

Bitte Machen Sie Ihren Code python-aussehend, mit Variablennamen. Wir sind alle alte, kurzsichtige, glastragende Kerle, und rohes JSON zu zerlegen tut wirklich weh. – DyZ

+0

Verwenden Sie eine 'for' -Schleife, um es zu tun. – furas

+0

Wie willst du deine 'all_projects': als Liste, als String, etc? – DyZ

Antwort

0

Sie kann zuerst ein Objekt dict über die Verwendung collections.defaultdict erstellen, um den eindeutigen Eintrag jedes "countryname" zu machen. Dann transformieren Sie die dict zu Ihrer gewünschten Antwort.

Zum Beispiel:

from collections import defaultdict 

country_project, country_sum = defaultdict(list), defaultdict(int) 

for country in country_list: 
    country_name = country["countryname"] 
    country_project[country_name].append(country['project_name']) 
    country_sum[country_name] += country['lendprojectcost'] 

# Map the `dict` to get desired result using list comprehension 
new_list = [ { 
     'countryname': country, 
     'project_name': country_project[country], 
     'lendprojectcost': country_sum[country]} for country in country_project] 

# OR, via using plain `for` loop as: 
# new_list = [] 
# for country in country_project: 
#  new_list.append({ 
#   'countryname': country, 
#   'project_name': country_project[country], 
#   'lendprojectcost': country_sum[country]}) 

wo country_list die ursprüngliche Liste in der Frage und der Endwert hält durch my_list erwähnt ist das gewünschte Ergebnis:

[{ 
    'countryname': 'Republic of Tunisia', 
    'project_name': [ 
     'TN: DTF Social Protection Reforms Support', 
     'Tunisia: Ecotourism and Conservation of Desert Biodiversity', 
     'Tunisia - Communications for policy reforms', 
     'Tunisia - Governance, Opportunities and Jobs DPL' 
    ], 
    'lendprojectcost': 515350000 
}] 
+1

Howabout 'new_list = [{'Ländername': Land, 'Projektname': Land_Projekt [Land], 'lendprojectcost': Land_sum [Land]} für Land in Land_Projekt]'. Listenergänzungen rulez. – DyZ

+0

@ DYZ: Ich dachte, es könnte für den Benutzer zu komplex sein. Aber nachdem ich deinen Kommentar gesehen und den zweiten Gedanken gemacht habe, denke ich, ich hätte das auch erwähnen sollen. Die Antwort wurde aktualisiert –

+0

Warte, was ist 'country_list'? – DyZ

0

Als Pandas Aussenseiter, würde ich für eine Pandas Lösung gehen: einen Datenrahmen aus den Originaldaten erstellen (nennen wir es raw), alle erforderlichen Aggregationen tun, und ein anderes Wörterbuch konstruieren:

df = pd.DataFrame(raw) 
result_df = df.groupby('countryname').agg({ 
         'lendprojectcost' : np.sum, 
         'project_name' : lambda col: col.tolist()}) 
result = result_df.reset_index().to_dict(orient="records") 

# [{"countryname":"Republic of Tunisia","project_name":["TN: DTF Social Protection Reforms Support","Tunisia: Ecotourism and Conservation of Desert Biodiversity","Tunisia - Communications for policy reforms","Tunisia - Governance, Opportunities and Jobs DPL"],"lendprojectcost":515350000}] 
0

Die anderen Antworten hier sind toll, aber das scheint ein natürliches Problem für reduce. Sie haben eine Liste, und Sie versuchen, die Elemente in der Liste mit Operationen zu kombinieren, um zu „reduzieren“, um die Liste Größe bis auf ein Element:

def update(x, y): 
    x["project_name"].append(y["project_name"]) 
    x["lendprojectcost"] += y["lendprojectcost"] 
    return x 

result = [reduce(update, list_of_dicts, {"countryname": "Republic of Tunisia", 
             "project_name": [], 
             "lendprojectcost": 0})] 

Bonus: Keine Importe erforderlich