如何将我的输出值添加到字典中

时间:2019-08-11 08:00:50

标签: python dictionary

我有我的代码来显示文件夹中的文件。如何插入字典

import os
result ={'T-Mobile':[],'iPhone':[]}
size = {22:[], 23:[]}
for (dirname,dirs,files) in os.walk('.'):
for filename in files:
    if filename.endswith('.txt'):
        thefile = os.path.join(dirname,filename)
        size =  (os.path.getsize(thefile),thefile)
        if size[0] == 22 :
            print ('T-Mobile:',thefile)
            result['T-Mobile'].append(thefile)
            continue
        if size[0] == 23 :
            print ('iPhone:', thefile)
            result['iPhone'].append(thefile)
            continue

我的出场

T-Mobile: .\Captures\a.txt
T-Mobile: .\Captures\b.txt
iPhone: .\Captures\c.txt
iPhone: .\Captures\d.txt

结果

{'T-Mobile': ['.\\Captures\\a.txt', '.\\Captures\\b.txt'],
 'iPhone': ['.\\Captures\\c.txt', '.\\Captures\\d.txt']}

所需

result ={'T-Mobile':['.\Captures\a.txt','.\Captures\b.txt'],'iPhone':['.\Captures\c.txt','.\Captures\d.txt']}                    
size = {22:['T-Mobile'], 23:['iPhone']}

size意味着,我们可以创建一个有关文件名和大小{22:['a.txt','g.txt'], 23:['b.txt']的字典,现在如何通过查找内部内容来创建字典

2 个答案:

答案 0 :(得分:0)

    list1 = list()
    list2 = list()
    dict_final_result = dict()
    ..................
    .................. 
    if size[0] == 22 :
        print ('T-Mobile:',thefile)
        continue
        #Append the value of thefile into a list
        list1.append(thefile)
    if size[0] == 23 :
        print ('iPhone:', thefile)
        #Append the value of thefile into a list
        list1.append(thefile)
        continue

    #Store the list elements into a dict with the appropriate key
    dict_final_result['T-Mobile'] = list1 
    dict_final_result['iPhone'] = list2

我将保留第二个字典的创建,该字典将大小存储为练习。相同的方法

答案 1 :(得分:0)

我只需将“ T-mobile”和“ iPhone”数据放入单独的列表中,然后将“ thefile”附加到特定列表中,如下所示:

import os
T_Mobile = []
iPhone = []
for (dirname,dirs,files) in os.walk('.'):
    for filename in files:
        if filename.endswith('.txt'):
            thefile = os.path.join(dirname,filename)
            size =  (os.path.getsize(thefile),thefile)
            if size[0] == 22 :
                print ('T-Mobile:',thefile)
                T_Mobile.append(thefile);
                continue
            if size[0] == 23 :
                print ('iPhone:', thefile)
                iPhone.append(thefile);
                continue

之后,您可以将两个列表放入for循环之后的字典中,如下所示:

result = {'T-Mobile': T_Mobile, 'iPhone': iPhone}