Accessing values from dictionaries nested in a list











up vote
0
down vote

favorite












First question here!



countries = [{'country': 'Italy', 'size':3,'reg':9},
{'country': 'Germany', 'size':7,'reg':1},
{'country': 'USA', 'size':9,'reg':4},
]

weights = {'size' : 100, 'reg' : 30}


I am trying to multiply values from the 'countries' nested dictionaries with the value associated with the matching key in the 'weights' dictionary. I tried a for loop approach as the values in 'weights' will be updated by the user.



I have tried this:



countries_weighted = copy.deepcopy(countries)

for key in weights.items():
for i in countries_weighted:
countries_weighted[i][key] *= weights[key]


That doesn't seem to work:



-
TypeError Traceback (most recent call last)
<ipython-input-52-9753dabe7648> in <module>()
13 for key in weights.items():
14 for i in countries_weighted:
---> 15 countries_weighted[i][key] *= weights[key]
16

TypeError: list indices must be integers or slices, not dict


Any idea? Thanks in advance.










share|improve this question
























  • for i in countries_weighted: will return the values in countries_weighted to your variable i, not the index. So in this case i gets an entire dictionary each time. So replacing countries_weighted[i][key] *= weights[key] with i[key] *= weights[key] should work for you. But Esteban Quiros's code below is much cleaner
    – Dan
    Nov 22 at 16:47















up vote
0
down vote

favorite












First question here!



countries = [{'country': 'Italy', 'size':3,'reg':9},
{'country': 'Germany', 'size':7,'reg':1},
{'country': 'USA', 'size':9,'reg':4},
]

weights = {'size' : 100, 'reg' : 30}


I am trying to multiply values from the 'countries' nested dictionaries with the value associated with the matching key in the 'weights' dictionary. I tried a for loop approach as the values in 'weights' will be updated by the user.



I have tried this:



countries_weighted = copy.deepcopy(countries)

for key in weights.items():
for i in countries_weighted:
countries_weighted[i][key] *= weights[key]


That doesn't seem to work:



-
TypeError Traceback (most recent call last)
<ipython-input-52-9753dabe7648> in <module>()
13 for key in weights.items():
14 for i in countries_weighted:
---> 15 countries_weighted[i][key] *= weights[key]
16

TypeError: list indices must be integers or slices, not dict


Any idea? Thanks in advance.










share|improve this question
























  • for i in countries_weighted: will return the values in countries_weighted to your variable i, not the index. So in this case i gets an entire dictionary each time. So replacing countries_weighted[i][key] *= weights[key] with i[key] *= weights[key] should work for you. But Esteban Quiros's code below is much cleaner
    – Dan
    Nov 22 at 16:47













up vote
0
down vote

favorite









up vote
0
down vote

favorite











First question here!



countries = [{'country': 'Italy', 'size':3,'reg':9},
{'country': 'Germany', 'size':7,'reg':1},
{'country': 'USA', 'size':9,'reg':4},
]

weights = {'size' : 100, 'reg' : 30}


I am trying to multiply values from the 'countries' nested dictionaries with the value associated with the matching key in the 'weights' dictionary. I tried a for loop approach as the values in 'weights' will be updated by the user.



I have tried this:



countries_weighted = copy.deepcopy(countries)

for key in weights.items():
for i in countries_weighted:
countries_weighted[i][key] *= weights[key]


That doesn't seem to work:



-
TypeError Traceback (most recent call last)
<ipython-input-52-9753dabe7648> in <module>()
13 for key in weights.items():
14 for i in countries_weighted:
---> 15 countries_weighted[i][key] *= weights[key]
16

TypeError: list indices must be integers or slices, not dict


Any idea? Thanks in advance.










share|improve this question















First question here!



countries = [{'country': 'Italy', 'size':3,'reg':9},
{'country': 'Germany', 'size':7,'reg':1},
{'country': 'USA', 'size':9,'reg':4},
]

weights = {'size' : 100, 'reg' : 30}


I am trying to multiply values from the 'countries' nested dictionaries with the value associated with the matching key in the 'weights' dictionary. I tried a for loop approach as the values in 'weights' will be updated by the user.



I have tried this:



countries_weighted = copy.deepcopy(countries)

for key in weights.items():
for i in countries_weighted:
countries_weighted[i][key] *= weights[key]


That doesn't seem to work:



-
TypeError Traceback (most recent call last)
<ipython-input-52-9753dabe7648> in <module>()
13 for key in weights.items():
14 for i in countries_weighted:
---> 15 countries_weighted[i][key] *= weights[key]
16

TypeError: list indices must be integers or slices, not dict


Any idea? Thanks in advance.







python python-3.x list dictionary for-loop






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 at 16:50









jpp

88k195099




88k195099










asked Nov 22 at 16:36









dpppstl

1




1












  • for i in countries_weighted: will return the values in countries_weighted to your variable i, not the index. So in this case i gets an entire dictionary each time. So replacing countries_weighted[i][key] *= weights[key] with i[key] *= weights[key] should work for you. But Esteban Quiros's code below is much cleaner
    – Dan
    Nov 22 at 16:47


















  • for i in countries_weighted: will return the values in countries_weighted to your variable i, not the index. So in this case i gets an entire dictionary each time. So replacing countries_weighted[i][key] *= weights[key] with i[key] *= weights[key] should work for you. But Esteban Quiros's code below is much cleaner
    – Dan
    Nov 22 at 16:47
















for i in countries_weighted: will return the values in countries_weighted to your variable i, not the index. So in this case i gets an entire dictionary each time. So replacing countries_weighted[i][key] *= weights[key] with i[key] *= weights[key] should work for you. But Esteban Quiros's code below is much cleaner
– Dan
Nov 22 at 16:47




for i in countries_weighted: will return the values in countries_weighted to your variable i, not the index. So in this case i gets an entire dictionary each time. So replacing countries_weighted[i][key] *= weights[key] with i[key] *= weights[key] should work for you. But Esteban Quiros's code below is much cleaner
– Dan
Nov 22 at 16:47












3 Answers
3






active

oldest

votes

















up vote
2
down vote













You could do it like this:



countries = [{'country': 'Italy', 'size':3,'reg':9},
{'country': 'Germany', 'size':7,'reg':1},
{'country': 'USA', 'size':9,'reg':4},
]

weights = {'size' : 100, 'reg' : 30}

for country in countries:
for key in weights.keys():
country[key] *= weights[key]

print(countries)





share|improve this answer























  • Makes sense.hank you Esteban Quiros, Dan and JPP for your help!
    – dpppstl
    Nov 23 at 15:12


















up vote
0
down vote













There are a couple of issues:





  1. dict.items cycles key-value pairs, not just keys;

  2. when you iterate countries_weighted you should use i.


So you can amend as follows:



for key, value in weights.items():
for i in countries_weighted:
i[key] *= value





share|improve this answer




























    up vote
    0
    down vote













    Only need to write countries_weighted[i][key] *= weights[key] as i[key] *= weights[key].






    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%2f53435144%2faccessing-values-from-dictionaries-nested-in-a-list%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
      2
      down vote













      You could do it like this:



      countries = [{'country': 'Italy', 'size':3,'reg':9},
      {'country': 'Germany', 'size':7,'reg':1},
      {'country': 'USA', 'size':9,'reg':4},
      ]

      weights = {'size' : 100, 'reg' : 30}

      for country in countries:
      for key in weights.keys():
      country[key] *= weights[key]

      print(countries)





      share|improve this answer























      • Makes sense.hank you Esteban Quiros, Dan and JPP for your help!
        – dpppstl
        Nov 23 at 15:12















      up vote
      2
      down vote













      You could do it like this:



      countries = [{'country': 'Italy', 'size':3,'reg':9},
      {'country': 'Germany', 'size':7,'reg':1},
      {'country': 'USA', 'size':9,'reg':4},
      ]

      weights = {'size' : 100, 'reg' : 30}

      for country in countries:
      for key in weights.keys():
      country[key] *= weights[key]

      print(countries)





      share|improve this answer























      • Makes sense.hank you Esteban Quiros, Dan and JPP for your help!
        – dpppstl
        Nov 23 at 15:12













      up vote
      2
      down vote










      up vote
      2
      down vote









      You could do it like this:



      countries = [{'country': 'Italy', 'size':3,'reg':9},
      {'country': 'Germany', 'size':7,'reg':1},
      {'country': 'USA', 'size':9,'reg':4},
      ]

      weights = {'size' : 100, 'reg' : 30}

      for country in countries:
      for key in weights.keys():
      country[key] *= weights[key]

      print(countries)





      share|improve this answer














      You could do it like this:



      countries = [{'country': 'Italy', 'size':3,'reg':9},
      {'country': 'Germany', 'size':7,'reg':1},
      {'country': 'USA', 'size':9,'reg':4},
      ]

      weights = {'size' : 100, 'reg' : 30}

      for country in countries:
      for key in weights.keys():
      country[key] *= weights[key]

      print(countries)






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 22 at 16:47

























      answered Nov 22 at 16:42









      Esteban Quiros

      1015




      1015












      • Makes sense.hank you Esteban Quiros, Dan and JPP for your help!
        – dpppstl
        Nov 23 at 15:12


















      • Makes sense.hank you Esteban Quiros, Dan and JPP for your help!
        – dpppstl
        Nov 23 at 15:12
















      Makes sense.hank you Esteban Quiros, Dan and JPP for your help!
      – dpppstl
      Nov 23 at 15:12




      Makes sense.hank you Esteban Quiros, Dan and JPP for your help!
      – dpppstl
      Nov 23 at 15:12












      up vote
      0
      down vote













      There are a couple of issues:





      1. dict.items cycles key-value pairs, not just keys;

      2. when you iterate countries_weighted you should use i.


      So you can amend as follows:



      for key, value in weights.items():
      for i in countries_weighted:
      i[key] *= value





      share|improve this answer

























        up vote
        0
        down vote













        There are a couple of issues:





        1. dict.items cycles key-value pairs, not just keys;

        2. when you iterate countries_weighted you should use i.


        So you can amend as follows:



        for key, value in weights.items():
        for i in countries_weighted:
        i[key] *= value





        share|improve this answer























          up vote
          0
          down vote










          up vote
          0
          down vote









          There are a couple of issues:





          1. dict.items cycles key-value pairs, not just keys;

          2. when you iterate countries_weighted you should use i.


          So you can amend as follows:



          for key, value in weights.items():
          for i in countries_weighted:
          i[key] *= value





          share|improve this answer












          There are a couple of issues:





          1. dict.items cycles key-value pairs, not just keys;

          2. when you iterate countries_weighted you should use i.


          So you can amend as follows:



          for key, value in weights.items():
          for i in countries_weighted:
          i[key] *= value






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 at 16:45









          jpp

          88k195099




          88k195099






















              up vote
              0
              down vote













              Only need to write countries_weighted[i][key] *= weights[key] as i[key] *= weights[key].






              share|improve this answer

























                up vote
                0
                down vote













                Only need to write countries_weighted[i][key] *= weights[key] as i[key] *= weights[key].






                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  Only need to write countries_weighted[i][key] *= weights[key] as i[key] *= weights[key].






                  share|improve this answer












                  Only need to write countries_weighted[i][key] *= weights[key] as i[key] *= weights[key].







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 4 at 9:10









                  mengxun

                  414




                  414






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53435144%2faccessing-values-from-dictionaries-nested-in-a-list%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

                      What visual should I use to simply compare current year value vs last year in Power BI desktop

                      Alexandru Averescu

                      Trompette piccolo