Loop through json array in string python











up vote
0
down vote

favorite












I have a string and I created a JSON array which contains strings and values:



amount = 0
a = "asaf,almog,arnon,elbar"
values_li={'asaf':'1','almog':'6','elbar':'2'}


How can I create a loop that will search all items on values_li in a and for each item it will find it will do



amount = amount + value(the value that found from value_li in a)


I tried to do this but it doesn't work:



for k,v in values_li.items():
if k in a:
amount = amount + v









share|improve this question
























  • ammount += int(v), you're trying to append a string. It would also be great if you in the future tell us why it isn't working by adding a traceback or description of the problem, not just what you want to achieve. I'm guessing tho that you're getting TypeError: unsupported operand type(s) for +: 'int' and 'str'. Hence my first part of my comment.
    – Torxed
    Nov 17 at 22:03












  • What do you mean by "it doesn't work"? What happens instead of what you want to happen?
    – mkrieger1
    Nov 17 at 22:03















up vote
0
down vote

favorite












I have a string and I created a JSON array which contains strings and values:



amount = 0
a = "asaf,almog,arnon,elbar"
values_li={'asaf':'1','almog':'6','elbar':'2'}


How can I create a loop that will search all items on values_li in a and for each item it will find it will do



amount = amount + value(the value that found from value_li in a)


I tried to do this but it doesn't work:



for k,v in values_li.items():
if k in a:
amount = amount + v









share|improve this question
























  • ammount += int(v), you're trying to append a string. It would also be great if you in the future tell us why it isn't working by adding a traceback or description of the problem, not just what you want to achieve. I'm guessing tho that you're getting TypeError: unsupported operand type(s) for +: 'int' and 'str'. Hence my first part of my comment.
    – Torxed
    Nov 17 at 22:03












  • What do you mean by "it doesn't work"? What happens instead of what you want to happen?
    – mkrieger1
    Nov 17 at 22:03













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have a string and I created a JSON array which contains strings and values:



amount = 0
a = "asaf,almog,arnon,elbar"
values_li={'asaf':'1','almog':'6','elbar':'2'}


How can I create a loop that will search all items on values_li in a and for each item it will find it will do



amount = amount + value(the value that found from value_li in a)


I tried to do this but it doesn't work:



for k,v in values_li.items():
if k in a:
amount = amount + v









share|improve this question















I have a string and I created a JSON array which contains strings and values:



amount = 0
a = "asaf,almog,arnon,elbar"
values_li={'asaf':'1','almog':'6','elbar':'2'}


How can I create a loop that will search all items on values_li in a and for each item it will find it will do



amount = amount + value(the value that found from value_li in a)


I tried to do this but it doesn't work:



for k,v in values_li.items():
if k in a:
amount = amount + v






python json






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 17 at 22:05









mkrieger1

4,19421832




4,19421832










asked Nov 17 at 22:00









אסף מזון

23




23












  • ammount += int(v), you're trying to append a string. It would also be great if you in the future tell us why it isn't working by adding a traceback or description of the problem, not just what you want to achieve. I'm guessing tho that you're getting TypeError: unsupported operand type(s) for +: 'int' and 'str'. Hence my first part of my comment.
    – Torxed
    Nov 17 at 22:03












  • What do you mean by "it doesn't work"? What happens instead of what you want to happen?
    – mkrieger1
    Nov 17 at 22:03


















  • ammount += int(v), you're trying to append a string. It would also be great if you in the future tell us why it isn't working by adding a traceback or description of the problem, not just what you want to achieve. I'm guessing tho that you're getting TypeError: unsupported operand type(s) for +: 'int' and 'str'. Hence my first part of my comment.
    – Torxed
    Nov 17 at 22:03












  • What do you mean by "it doesn't work"? What happens instead of what you want to happen?
    – mkrieger1
    Nov 17 at 22:03
















ammount += int(v), you're trying to append a string. It would also be great if you in the future tell us why it isn't working by adding a traceback or description of the problem, not just what you want to achieve. I'm guessing tho that you're getting TypeError: unsupported operand type(s) for +: 'int' and 'str'. Hence my first part of my comment.
– Torxed
Nov 17 at 22:03






ammount += int(v), you're trying to append a string. It would also be great if you in the future tell us why it isn't working by adding a traceback or description of the problem, not just what you want to achieve. I'm guessing tho that you're getting TypeError: unsupported operand type(s) for +: 'int' and 'str'. Hence my first part of my comment.
– Torxed
Nov 17 at 22:03














What do you mean by "it doesn't work"? What happens instead of what you want to happen?
– mkrieger1
Nov 17 at 22:03




What do you mean by "it doesn't work"? What happens instead of what you want to happen?
– mkrieger1
Nov 17 at 22:03












3 Answers
3






active

oldest

votes

















up vote
0
down vote













It's working.
I figure out my problem.
v is a string and I tried to do math with a string so I had to convert v to an int



amount = amount + int(v)


Now It's working :)






share|improve this answer




























    up vote
    0
    down vote













    You should be careful using:



    if k in a:


    a is the string: "asaf,almog,arnon,elbar" not a list. This means that:



    "bar" in a # == True
    "as" in a # == True



    ..etc Which is probably not what you want.



    You should consider splitting it into an array, then you'll only get complete matches. With that you can simply use:



    a = "asaf,almog,arnon,elbar".split(',')
    values_li={'asaf':'1','almog':'6','elbar':'2'}

    amount = sum([int(values_li[k]) for k in a if k in values_li])
    # 9





    share|improve this answer




























      up vote
      0
      down vote













      collections.Counter() is your friend:



      from collections import Counter
      a = "asaf,almog,arnon,elbar"
      values_li = Counter({'asaf':1,'almog':6,'elbar':2})
      values_li.update(a.split(','))
      values_li


      That will result in:



      Counter({'almog': 7, 'elbar': 3, 'asaf': 2, 'arnon': 1})


      And if you want the sum of all values in values_li, you can simply do:



      sum(values_li.values())


      Which will result in 13, for the key/value pairs in your example.






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














         

        draft saved


        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53355949%2floop-through-json-array-in-string-python%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        0
        down vote













        It's working.
        I figure out my problem.
        v is a string and I tried to do math with a string so I had to convert v to an int



        amount = amount + int(v)


        Now It's working :)






        share|improve this answer

























          up vote
          0
          down vote













          It's working.
          I figure out my problem.
          v is a string and I tried to do math with a string so I had to convert v to an int



          amount = amount + int(v)


          Now It's working :)






          share|improve this answer























            up vote
            0
            down vote










            up vote
            0
            down vote









            It's working.
            I figure out my problem.
            v is a string and I tried to do math with a string so I had to convert v to an int



            amount = amount + int(v)


            Now It's working :)






            share|improve this answer












            It's working.
            I figure out my problem.
            v is a string and I tried to do math with a string so I had to convert v to an int



            amount = amount + int(v)


            Now It's working :)







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 17 at 22:17









            אסף מזון

            23




            23
























                up vote
                0
                down vote













                You should be careful using:



                if k in a:


                a is the string: "asaf,almog,arnon,elbar" not a list. This means that:



                "bar" in a # == True
                "as" in a # == True



                ..etc Which is probably not what you want.



                You should consider splitting it into an array, then you'll only get complete matches. With that you can simply use:



                a = "asaf,almog,arnon,elbar".split(',')
                values_li={'asaf':'1','almog':'6','elbar':'2'}

                amount = sum([int(values_li[k]) for k in a if k in values_li])
                # 9





                share|improve this answer

























                  up vote
                  0
                  down vote













                  You should be careful using:



                  if k in a:


                  a is the string: "asaf,almog,arnon,elbar" not a list. This means that:



                  "bar" in a # == True
                  "as" in a # == True



                  ..etc Which is probably not what you want.



                  You should consider splitting it into an array, then you'll only get complete matches. With that you can simply use:



                  a = "asaf,almog,arnon,elbar".split(',')
                  values_li={'asaf':'1','almog':'6','elbar':'2'}

                  amount = sum([int(values_li[k]) for k in a if k in values_li])
                  # 9





                  share|improve this answer























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    You should be careful using:



                    if k in a:


                    a is the string: "asaf,almog,arnon,elbar" not a list. This means that:



                    "bar" in a # == True
                    "as" in a # == True



                    ..etc Which is probably not what you want.



                    You should consider splitting it into an array, then you'll only get complete matches. With that you can simply use:



                    a = "asaf,almog,arnon,elbar".split(',')
                    values_li={'asaf':'1','almog':'6','elbar':'2'}

                    amount = sum([int(values_li[k]) for k in a if k in values_li])
                    # 9





                    share|improve this answer












                    You should be careful using:



                    if k in a:


                    a is the string: "asaf,almog,arnon,elbar" not a list. This means that:



                    "bar" in a # == True
                    "as" in a # == True



                    ..etc Which is probably not what you want.



                    You should consider splitting it into an array, then you'll only get complete matches. With that you can simply use:



                    a = "asaf,almog,arnon,elbar".split(',')
                    values_li={'asaf':'1','almog':'6','elbar':'2'}

                    amount = sum([int(values_li[k]) for k in a if k in values_li])
                    # 9






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 17 at 22:28









                    Mark Meyer

                    29.8k32549




                    29.8k32549






















                        up vote
                        0
                        down vote













                        collections.Counter() is your friend:



                        from collections import Counter
                        a = "asaf,almog,arnon,elbar"
                        values_li = Counter({'asaf':1,'almog':6,'elbar':2})
                        values_li.update(a.split(','))
                        values_li


                        That will result in:



                        Counter({'almog': 7, 'elbar': 3, 'asaf': 2, 'arnon': 1})


                        And if you want the sum of all values in values_li, you can simply do:



                        sum(values_li.values())


                        Which will result in 13, for the key/value pairs in your example.






                        share|improve this answer



























                          up vote
                          0
                          down vote













                          collections.Counter() is your friend:



                          from collections import Counter
                          a = "asaf,almog,arnon,elbar"
                          values_li = Counter({'asaf':1,'almog':6,'elbar':2})
                          values_li.update(a.split(','))
                          values_li


                          That will result in:



                          Counter({'almog': 7, 'elbar': 3, 'asaf': 2, 'arnon': 1})


                          And if you want the sum of all values in values_li, you can simply do:



                          sum(values_li.values())


                          Which will result in 13, for the key/value pairs in your example.






                          share|improve this answer

























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            collections.Counter() is your friend:



                            from collections import Counter
                            a = "asaf,almog,arnon,elbar"
                            values_li = Counter({'asaf':1,'almog':6,'elbar':2})
                            values_li.update(a.split(','))
                            values_li


                            That will result in:



                            Counter({'almog': 7, 'elbar': 3, 'asaf': 2, 'arnon': 1})


                            And if you want the sum of all values in values_li, you can simply do:



                            sum(values_li.values())


                            Which will result in 13, for the key/value pairs in your example.






                            share|improve this answer














                            collections.Counter() is your friend:



                            from collections import Counter
                            a = "asaf,almog,arnon,elbar"
                            values_li = Counter({'asaf':1,'almog':6,'elbar':2})
                            values_li.update(a.split(','))
                            values_li


                            That will result in:



                            Counter({'almog': 7, 'elbar': 3, 'asaf': 2, 'arnon': 1})


                            And if you want the sum of all values in values_li, you can simply do:



                            sum(values_li.values())


                            Which will result in 13, for the key/value pairs in your example.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 17 at 22:41

























                            answered Nov 17 at 22:36









                            accdias

                            38229




                            38229






























                                 

                                draft saved


                                draft discarded



















































                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53355949%2floop-through-json-array-in-string-python%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                If I really need a card on my start hand, how many mulligans make sense? [duplicate]

                                Alcedinidae

                                Can an atomic nucleus contain both particles and antiparticles? [duplicate]