简体   繁体   English

遍历python中的字典值

[英]Iterating through dictionary values in python

I have 1000+ text files, each with two columns, one being dates, the other stock prices (at respective date).我有 1000 多个文本文件,每个文件有两列,一列是日期,另一列是股票价格(在各自的日期)。 I have uploaded them and cast them into a dictionary using the following code:我已经上传它们并使用以下代码将它们转换为字典:

filelist = os.listdir(r'insertfilepath')
filepath = r'insertfilepath'

dic1 = {}

for file in filelist:
    df = pd.read_csv(filepath + file,sep='\t')
    dic1[file]= df

However, when I try to change the column names for each one using the following code:但是,当我尝试使用以下代码更改每个列名时:

for value in dic1:
    for df in value: 
        df.rename(columns={df.columns[0]:'Dates',df.columns[1]:'Prices'},inplace=True)

I get the following error: 'str' object has no attribute 'rename'.我收到以下错误:'str' 对象没有属性 'rename'。

Interestingly this worked when I casted it to a list, but a I can't analyze the data in a list because I have no way of knowing which stock matches what data.有趣的是,当我将其转换为列表时,这有效,但是我无法分析列表中的数据,因为我无法知道哪只股票与哪些数据匹配。

Any help would be greatly appreciated.任何帮助将不胜感激。 I'm new to python so please go easy.我是python的新手,所以请放轻松。 Thanks谢谢

for value in dic1 loops through the keys, which are file name strings in this case. for value in dic1循环遍历键,在这种情况下是文件名字符串。 You want for value in dic1.values()您想要for value in dic1.values()

If you want both keys and values, you use dic1.items() which returns (key, value) tuples如果你想要键和值,你可以使用dic1.items()返回 (key, value) 元组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM