2016-08-08 53 views
1

Dies ist, wie meine Eingabe wie folgt aussieht:Vergleichsliste oder setzen auf einen Teil des JSON-Objekt

inputData=[] 
inputData.append({"CustomerName": "CustomerA","State": "StateA","ItemNumber": "Item1"}) 
inputData.append({"CustomerName": "CustomerA","State": "StateA","ItemNumber": "Item2"}) 
inputData.append({"CustomerName": "CustomerB","State": "StateB","ItemNumber": "Item1"}) 
inputData.append({"CustomerName": "CustomerB","State": "StateB","ItemNumber": "Item2"}) 
inputData.append({"CustomerName": "CustomerX","State": "StateX","ItemNumber": "Item1"}) 
inputData.append({"CustomerName": "CustomerX","State": "StateX","ItemNumber": "Item2"}) 

Dies ist die Liste, die ich gegen bin im Vergleich um herauszufinden, ob der Kunde darf das Produkt kaufen oder nicht .

allowedCustomers = ["CustomberA","CustomberB"] 

Dies ist, wie ich die Listen bin im Vergleich:

unauthorizedCustomers = list(set(inputData)-set(allowedCustomers)) 

Wie obige Aussage kann so ändern, dass der Vergleich nur auf Kundennamen geschieht aber unauthorizedCustomers Liste CustomerX vollständige Daten s‘?

[{"CustomerName": "CustomerX","State": "StateX","ItemNumber": "Item1"}, 
{"CustomerName": "CustomerX","State": "StateX","ItemNumber": "Item2"})] 

Antwort

1
>>> inputCustomerNames = [ item['CustomerName'] for item in inputData ] # get a list of input customer names only 
>>> unauthorizedCustomers = list(set(inputCustomerNames) - set(allowedCustomers)) # find unauthorized customers 
>>> unauthorizedCustomersDetails = [ item for item in inputData if item['CustomerName'] in unauthorizedCustomers ] # get all data of unauthorized customers 

Sie sollten über Listenkomprehensionen zu verstehen, lesen, was hier geschieht. List Comprehensions

1

Hier ist, was Sie json und Listen mit tun können:

import json 
inputData=[] 
inputData.append({"CustomerName": "CustomerA","State": "StateA","ItemNumber": "Item1"}) 
inputData.append({"CustomerName": "CustomerA","State": "StateA","ItemNumber": "Item2"}) 
inputData.append({"CustomerName": "CustomerB","State": "StateB","ItemNumber": "Item1"}) 
inputData.append({"CustomerName": "CustomerB","State": "StateB","ItemNumber": "Item2"}) 
inputData.append({"CustomerName": "CustomerX","State": "StateX","ItemNumber": "Item1"}) 
inputData.append({"CustomerName": "CustomerX","State": "StateX","ItemNumber": "Item2"}) 

allowedCustomers = ["CustomerA","CustomerB"] 
json_array = json.loads(json.dumps(inputData)) 
# Now filter required customer based on specific property. 
allowed_customers = [customer for customer in json_array if customer['CustomerName'] in allowedCustomers]