简体   繁体   English

如何将文件的大小和名称放入字典

[英]How to put my size and name of a file into dictionary

I have 3 files size_1.py size_2.py size.py 我有3个文件size_1.py size_2.py size.py

My Code is below 我的代码如下

import os
result = {}
for (dirname,dirs,files) in os.walk('.'):
    for filename in files:
        if filename.endswith('.py'):
            thefile = os.path.join(dirname,filename)
            size =  (os.path.getsize(thefile),thefile)
           # print (size)
            result[size[0]] = size[1]
print (result)

My output 我的输出

{315: './size.py', 249: './size_1.py'}

My Desired Output 我想要的输出

{315:['./size.py']
249 : ['size_1.py', './size_2.py']
}

You only put strings in the values of result dictionary. 您只将字符串放入result字典的值中。 You should put lists of strings. 您应该放置字符串列表。 To do so, I suggest you to use defaultdict class to define directly a dictionary with lists as values, which is more comfortable. 为此,我建议您使用defaultdict类直接定义一个将列表作为值的字典,这样更方便。
I may also suggest you some minor improvements in your code for readability, as follows: 我还建议您对代码进行一些小的改进以提高可读性,如下所示:

import os
from collections import defaultdict

result = defaultdict(list)
for (dirname,dirs,files) in os.walk('.'):
   for filename in files:
        if filename.endswith('.py'):
            thefile = os.path.join(dirname,filename)
            size =  os.path.getsize(thefile)
            result[size].append(thefile)
print (result)

You can use a defaultdict of list to easily do this, just append values instead of assigning. 您可以使用list的defaultdict轻松地做到这一点,只需附加值而不是赋值即可。

import os
from collections import defaultdict
result = defaultdict(list)
for (dirname,dirs,files) in os.walk('.'):
    for filename in files:
        if filename.endswith('.py'):
            thefile = os.path.join(dirname,filename)
            size =  (os.path.getsize(thefile),thefile)
           # print (size)
            result[size[0]].append(size[1])
print (result)

Alternatively, without using defaultdict: 或者,不使用defaultdict:

import os
result = {}
for (dirname,dirs,files) in os.walk('.'):
    for filename in files:
        if filename.endswith('.py'):
            thefile = os.path.join(dirname,filename)
            size =  (os.path.getsize(thefile),thefile)
           # print (size)
            result.setdefault(size[0], []).append(size[1])
print (result)

You can just add an if check to see if the key (size) exists in dictionary already: 您可以添加一个if检查以查看字典中是否已经存在键(大小):

import os
result = {}
for (dirname,dirs,files) in os.walk('.'):
    for filename in files:
        if filename.endswith('.py'):
            thefile = os.path.join(dirname,filename)
            size =  (os.path.getsize(thefile),thefile)
           # print (size)
        if size[0] in result:
            result[size[0]].append(size[1])
        else:
            result[size[0]] = [size[1]]
print (result)

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

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