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



(注意:这使用ESRI arcpy。描述(

我有一本空字典,说它叫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']}

我希望这能有所帮助,也很重要!