两个列表:一个字典-将一个列表(值)中的项目插入字典中的键中

注意:这使用了ESRI arcpy.Describe

我有一个空字典,说它叫 file_dict

我有两个列表:1.一个列表是我将用作 typelist 的键的文件类型的列表。  2.第二个是文件夹中的文件列表,名为 fileList

我能够:  将 typelist 放入字典中作为键。

file_dict.keys()
[u'Layer',u'Dbasetable',u'ShapeFile',u'File',u'TextFile',u'RasterDataset']

我需要以下方面的帮助: 使用比较检查以下内容:(伪编码)

FOR each file in fileList:
    CHECK the file type 
''' using arcpy.Describe -- I have a variable already called desc - it is how I got typelist '''
    IF file is a particular type (say shapefile):
        INSERT that value from fileList into a list within the appropriate typelist KEY in file_dict
    ENDIF
ENDFOR

我希望的file_dict输出为:

    >>> file_dict
    {
u'Layer': ['abd.lyr','123.lyr'],u'Dbasetable': ['ABD.dbf'],u'ShapeFile': ['abc.shp','123.shp'],u'File': ['123.xml'],u'TextFile': ['ABC.txt','123.txt'],u'RasterDataset': ['ABC.jpg','123.TIF']
}

注意:我想避免压缩。 (我觉得比较容易,但是...)

qq1988110 回答:两个列表:一个字典-将一个列表(值)中的项目插入字典中的键中

如果您想使用简单的Python脚本来完成此操作,

# Input
file_list = ['abd.lyr','123.lyr','ABD.dbf','abc.shp','123.shp','123.xml','ABC.jpg','123.TIF','ABC.txt','123.txt'
            ]

# Main code
file_dict = {} #dict declaration


case = {
    'lyr': "Layer",'dbf': "DbaseTable",'shp': "ShapeFile",'xml': "File",'txt': "TextFile",'jpg': "RasterDataset",'TIF': "RasterDataset",} # Case declaration for easy assignment


for i in file_list:
    file_dict.setdefault(case[i.split(".")[-1]],[]).append(i) # appending files to the case identified using setdefault method.

print (file_dict)

# Output
# {'Layer': ['abd.lyr','123.lyr'],'DbaseTable': ['ABD.dbf'],'ShapeFile': ['abc.shp','123.shp'],'File': ['123.xml'],'RasterDataset': ['ABC.jpg','123.TIF'],'TextFile': ['ABC.txt','123.txt']}

我希望这对您有所帮助!

本文链接:https://www.f2er.com/3148304.html

大家都在问