Python 3.x Python 3-文件作为字典导入,但值是列表-如何解析?

Python 3.x Python 3-文件作为字典导入,但值是列表-如何解析?,python-3.x,list,dictionary,Python 3.x,List,Dictionary,我正在将文件夹中的文件作为字典导入python,其中 键=文件名,值=文件内容 e、 g mydict = {'File1': ['this is a string as a list'], 'File2': ['second string in file 2 is also a list']} 而我想要的是: mydict = {'File1': 'this is a string as a list', 'File2:': '...'} 我还想计算以下字符串:string,这是在数据结

我正在将文件夹中的文件作为字典导入python,其中 键=文件名,值=文件内容

e、 g

mydict = {'File1': ['this is a string as a list'], 
'File2': ['second string in file 2 is also a list']}
而我想要的是:

mydict = {'File1': 'this is a string as a list', 'File2:': '...'}
我还想计算以下字符串:string,这是在数据结构中输出它的第二个字符串。我猜我需要使用集合中的计数器来实现这一点——但我是否首先需要标记我的值

将文本导入字典的代码:

filenames = os.listdir('.')
file_dict = {}
for file in filenames:
    with open(file) as f:
        items = [i.strip() for i in f.read().split(",")]
    file_dict[file.replace(".txt", "")] = items

print(file_dict)
若要使值全部小写,则无法执行,因为它们位于列表中:

#convert dictionary to lower case
def lower_dict(d):
   new_dict = dict((k, v.lower()) for k, v in d.items())
   return new_dict
print(lower_dict(file_dict))
AttributeError:“list”对象没有属性“lower”


非常感谢您的帮助。

您在加载输入时正在拆分输入:

items = [i.strip() for i in f.read().split(",")]
如果只需要文件内容,则可以使用:

items = f.read()
如果仍要修剪逗号、周围的空格,则可以将其与str.join重新组合


非常感谢你!这起作用了。不过,快速提问-我的价值观中有很多\n。这会影响像计算字符串这样的事情吗,还是仅仅是python在控制台中的显示方式?例如,如果我想计算texas出现的次数,但我可以在控制台中看到该值显示为\n唯一-不计数吗?\n是换行符的转义码。如果您只是搜索单词,这可能不会影响计数,但是在其他应用程序中可能会出现问题。您是对的-它不会影响计数,只是检查了一下,非常感谢!
items = ','.join([i.strip() for i in f.read().split(",")])    # This will reinsert commas
items = ''.join([i.strip() for i in f.read().split(",")])     # This will not