2021年1月26日星期二

What does stocks[key] = val.replace('$', '') mean?

I'm studying a Python book, 'The Data Wrangling Workshop' published by Packt. I'm stuck on one of the exercises because I'm not sure what a particular line of code means. See transcript below.

In this exercise, we are going to iterate over a dictionary and print the values and keys. To do so, let's go through the following steps:

  1. Open a new Jupyter Notebook and define a dictionary with the key provided along with it. Keep in mind there is no given order for any pair in the dictionary:

    "Zoe's Kitchen, Inc.":"$262.32M",  "Toyota Motor Corp Ltd Ord":"$156.02B",      "Nuveen Virginia Quality Municipal Income Fund":"$238.33M",  "Kinross Gold Corporation":"$5.1B",  "Vulcan Materials Company":"$17.1B",  "Hi-Crush Partners LP":"$955.69M",  "Lennox International, Inc.":"$8.05B",  "WMIH Corp.":"$247.66M",  "Comerica Incorporated":"n/a"}    
  2. Remove the $ character from the stocks dictionary:

    for key,val in stocks.items():          stocks[key] = val.replace('$', '')          stocks  

I understand the first line of code but I'm puzzled at the first part of the second line. What does stocks[key] mean? If I read it like it's written it seems like the '$' is being replaced with an empty character and it's assigned a new key-value? I'm just not sure what that piece is doing here. Can anyone explain?

https://stackoverflow.com/questions/65912745/what-does-stockskey-val-replace-mean January 27, 2021 at 12:05PM

没有评论:

发表评论