[英]What is the best way to create variables from a dict
To be able to increase my dictionary while not changing much else in the code, I want to iterate through the dictionary keys and create dataframes.为了能够增加我的字典而不改变代码中的其他内容,我想遍历字典键并创建数据框。
The way I have found is through creating global variables with global().我发现的方法是通过使用 global() 创建全局变量。 However, is this the most pythonic way, or the best way?
然而,这是最 Pythonic 的方式,还是最好的方式? I know global variables are a nono, but it seems to be the only fix here.
我知道全局变量是一个 nono,但它似乎是这里唯一的解决方法。
stocks = {
'Tencent':'TCEHY',
'Blizzard' : 'ATVI',
'EA':'EA',
'Rockstar':'TTWO'
}
def create_dataframes(stock_dict):
for stock in stock_dict:
globals()[stock] = pd.read_csv('{}.csv'.format(stock_dict[stock]))
This results in new variables with the key names, which is of course what I want.这会产生带有键名的新变量,这当然是我想要的。 I just want to know if I should do this in another way?
我只是想知道我是否应该以另一种方式这样做?
Thanks!谢谢!
Don't create global variables at runtime, just use a dictionary.不要在运行时创建全局变量,只需使用字典。
dfs = {}
for stock_name, stock_code in stock_dict.items():
dfs[stock_name] = pd.read_csv(f'{stock_code}.csv')
You can then access them using their names然后,您可以使用他们的名字访问它们
dfs['EA'].describe()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.