遍历一个dicts列表并更新项目的数量

时间:2017-11-19 10:58:29

标签: json python-3.x

我有一个从json API获取的购买列表,如下所示:

public class MainActivity extends AppCompatActivity {
private WebView mWebviewPop;
private WebView view;
private FrameLayout mContainer;
private Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    view = (WebView) this.findViewById(R.id.webView);
    mContainer = (FrameLayout) findViewById(R.id.webview_frame);
    view.getSettings().setJavaScriptEnabled(true);
    view.getSettings().setUserAgentString("Mozilla/5.0 (Linux; Android 4.4.2; ZTE T221 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.85 Mobile Safari/537.36");
    view.getSettings().setAppCacheEnabled(true);
    view.getSettings().setLoadWithOverviewMode(true);
    view.getSettings().setUseWideViewPort(true);
    view.getSettings().setDatabaseEnabled(true);
    view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    view.getSettings().setSupportMultipleWindows(true);
    view.getSettings().setAllowFileAccess(true);
    view.getSettings().setDomStorageEnabled(true);
    view.invalidate();
    view.setWebViewClient(new MyBrowser() {
    });
    view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    view.loadUrl("http://mysite");
    view.setWebChromeClient(new UriChromeClient() {
    });
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (!prefs.getBoolean("firstTime", false)) {
        Intent alarmIntent = new Intent(this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 18);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 1);
        manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, pendingIntent);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("firstTime", true);
        editor.apply();
    }
    mContext=this.getApplicationContext();
}


private class MyBrowser extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mailto:") || url.startsWith("mms:") || url.startsWith("mmsto:") || url.startsWith("market:") || url.startsWith("https://youtu")) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        } else {
            view.loadUrl(url);
            return true;
        }
    }
    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler,
                                   SslError error) {
        Log.d("onReceivedSslError", "onReceivedSslError");
        //super.onReceivedSslError(view, handler, error);
    }

}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK) && view.canGoBack()) {
        view.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
class UriChromeClient extends WebChromeClient {
    @Override
    public boolean onCreateWindow(WebView view, boolean isDialog,
                                  boolean isUserGesture, Message resultMsg) {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        mWebviewPop = new WebView(mContext);
        mWebviewPop.setVerticalScrollBarEnabled(false);
        mWebviewPop.getSettings().setLoadWithOverviewMode(true);
        mWebviewPop.getSettings().setUseWideViewPort(true);
        mWebviewPop.setHorizontalScrollBarEnabled(false);
        mWebviewPop.setWebViewClient(new MyBrowser());
        mWebviewPop.getSettings().setDatabaseEnabled(true);
        mWebviewPop.getSettings().setJavaScriptEnabled(true);
        mWebviewPop.getSettings().setSavePassword(true);
        mWebviewPop.getSettings().setAppCacheEnabled(true);
        mWebviewPop.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebviewPop.getSettings().setSupportMultipleWindows(true);
        mWebviewPop.getSettings().setAllowFileAccess(true);
        mWebviewPop.getSettings().setDomStorageEnabled(true);
        mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        mContainer.addView(mWebviewPop);
        WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
        transport.setWebView(mWebviewPop);
        resultMsg.sendToTarget();
        return true;
    }

    @Override
    public void onCloseWindow(WebView window) {
        Log.d("onCloseWindow", "called");
    }
}

我想要做的是获得以下输出,其中[{'quantity': '7', 'productUuid': '12345', 'unitPrice': 1234, 'name': 'apple'}, {'quantity': '7', 'productUuid': '12346', 'unitPrice': 4321, 'name': 'orange'}, {'quantity': '5', 'productUuid': '12345', 'unitPrice': 1234, 'name': 'apple'}] 被比较,并且为同一productUuid添加了数量以反映所述产品的总销售额:

productUuid

我尝试了以下操作,将相关的键和值复制到一个列表中(我认为)更容易操作,但它不起作用,我觉得可能更容易解决我的问题。

[{'quantity': '12', 'productUuid': '12345', 'unitPrice': 1234, 'name': 'apple'}, {'quantity': '7', 'productUuid': '12346', 'unitPrice': 4321, 'name': 'orange'}]

感谢您的建议!

1 个答案:

答案 0 :(得分:0)

最后花了更多的时间来完成它。我首先创建了一个uuids列表,然后迭代它以添加数量。

def add_quantities(json_list):
    '''adds quantities for the same productUuid and returns a new dict with total quantities for each product'''

    # create a list to store uuids and another to store purchase dicts
    uuids = []
    list_of_totals = []

    for purchase in json_list:
        if purchase['productUuid'] not in uuids:
            uuids.append(purchase['productUuid'])


    # iterate through list of uuids against dict and add quantities for corresponding uuids

    for uuid in uuids:
        uuid_qty = 0
        totals = {}
        for purchase in json_list:
            if uuid in purchase['productUuid']:
                uuid_qty = uuid_qty + int(purchase['quantity'])
                unitPrice = purchase['unitPrice']
                name = purchase['name']
                totals.update({'productUuid': uuid, 'quantity': uuid_qty, 'unitPrice': unitPrice, 'name': name})

        list_of_totals.append(totals)

    return list_of_totals

欢迎任何使这更好的想法。