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

Two Lists: One Dictionary - Insert item(s) from one list (values) into keys within a dictionary

(注意:这使用了 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']
}

注意:我想避免压缩。 (我知道它更容易但是......)

如果您想使用简单的 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']}

我希望这对您有所帮助并且很重要!