首页 > 解决方案 > 将字典项插入字典列表

问题描述

我有adImageList以下形式的字典项目列表:

[{'Image_thumb_100x75': 'https://cache.domain.com/mmo/7/295/170/227_174707044_thumb.jpg',
  'Image_hoved_400x300': 'https://cache.domain.com/mmo/7/295/170/227_174707044_hoved.jpg',
  'Image_full_800x600': 'https://cache.domain.com/mmo/7/295/170/227_174707044.jpg'},
 {'Image_thumb_100x75': 'https://cache.domain.com/mmo/7/295/170/227_1136648194_thumb.jpg',
  'Image_hoved_400x300': 'https://cache.domain.com/mmo/7/295/170/227_1136648194_hoved.jpg',
  'Image_full_800x600': 'https://cache.domain.com/mmo/7/295/170/227_1136648194.jpg'},
 {'Image_thumb_100x75': 'https://cache.domain.com/mmo/7/295/170/227_400613427_thumb.jpg',
  'Image_hoved_400x300': 'https://cache.domain.com/mmo/7/295/170/227_400613427_hoved.jpg',
  'Image_full_800x600': 'https://cache.domain.com/mmo/7/295/170/227_400613427.jpg'}]

我有迭代器,它假设在从网络获取它之后在每个图像记录下添加本地 URL(获取部分工作正常)。因此,我使用以下代码将本地 URL 附加到现有字典项:

 for i, d in enumerate(adImageList):
                file_name_thumb = '0{}_{}_{}'.format(i, page_title,'_thumb_100x75.jpg')
                urllib.request.urlretrieve(d['Image_thumb_100x75'], file_name_thumb)
                local_path_thumb = dir_path+file_name_thumb
                adImageList.insert[i](1,{'Image_thumb_100x75_local_path_thumb':local_path_thumb}) # not working

                file_name_hoved = '0{}_{}_{}'.format(i, page_title,'_hoved_400x300.jpg')
                urllib.request.urlretrieve(d['Image_hoved_400x300'], file_name_hoved)
                local_path_hoved = dir_path+file_name_hoved
                adImageList.insert[i](3,{'Image_hoved_400x300_local_path_hoved':local_path_hoved}) # not working

                file_name_full = '0{}_{}_{}'.format(i, page_title,'_full_800x600.jpg')
                urllib.request.urlretrieve(d['Image_full_800x600'], file_name_full)
                local_path_full = dir_path+file_name_full
                adImageList.insert[i](5,{'Image_full_800x600_local_path_full':local_path_full}) # not working

想法是以下列方式扩展 dict 项目,这也解释了我的代码中的数字 1,3 和 5

{'Image_thumb_100x75': 'https://cache.domain.com/mmo/7/295/170/227_174707044_thumb.jpg',
  'Image_thumb_100x75_local_path_thumb':local_path_thumb #1,
  'Image_hoved_400x300': 'https://cache.domain.com/mmo/7/295/170/227_174707044_hoved.jpg',
  'Image_hoved_400x300_local_path_hoved':local_path_hoved #3
  'Image_full_800x600': 'https://cache.domain.com/mmo/7/295/170/227_174707044.jpg',
  'Image_full_800x600_local_path_full':local_path_full #5}

但这给了我错误:

TypeError:“builtin_function_or_method”对象不可下标

标签: pythonpython-3.xlistdictionary

解决方案


很可能这是您的想法:

adImageList[i]['Image_thumb_100x75_local_path_thumb']=local_path_thumb

这会将键添加'Image_thumb_100x75_local_path_thumb'i列表中的第 th 个字典并将其值设置为local_path_thumb。1,3,5 的用途还不清楚。


推荐阅读