简体   繁体   English

从字典值创建新字典

[英]Creating new dictionary from dictionaries value

I have the following values in a list: 我在列表中有以下值:

'image_result': [{'checksum': '701e172bd980177ae1311f265a753582',
               'path': 'full/ee4d4341b88168972e76c61f45b8db10b349f175.jpg',
               'url': 'http://image-url.com/ID71026700-0000-0500-0000-0000033eb03c.jpg'},
              {'checksum': 'e0b3cada2a8377913bc779a16f1d9e36',
               'path': 'full/410c964db8de6138622c1e1b3b94062b69caedc8.jpg',
               'url': 'image-url.com/ID71026700-0000-0500-0000-0000033eb03d.jpg'},
              {'checksum': '39c9a06f221ba584f691f0def0fde2c4',
               'path': 'full/574dcb9a6af1ea7b733e6986c6a10ba815ca23b4.jpg',
               'url': 'image-url.com/ID71026700-0000-0500-0000-0000033eb03e.jpg'}]

I'd like to get the 'path' value and format it to the following so it becomes a global image key: 我想获取“路径”值并将其格式化为以下格式,以便它成为全局image键:

'image': 'full/ee4d4341b88168972e76c61f45b8db10b349f175.jpg',
'image': 'full/ee4d4341b88168972e76c61f45b8db10b349f175.jpg',
'image': 'full/574dcb9a6af1ea7b733e6986c6a10ba815ca23b4.jpg'

The code I have gives me the right output as shown above, but it only saves the last 'path' value because it's overwritten in each cycle of the loop: 我得到的代码为我提供了如上所示的正确输出,但是它只保存了最后一个“路径”值,因为在循环的每个循环中它都被覆盖了:

for x in item['image_result']:
   item['image'] = x.get('path')

These are Scrapy items and haven't been able to figure out if this is possible without overwriting the item value every time I want to insert a new one. 这些是Scrapy项目,每次我想插入一个新项目时,都无法弄清楚是否有可能不覆盖项目值。 I'm also very new to python and haven't found a way to get around this even though I researched a lot in the last few days. 我对python还是很陌生,即使最近几天我做了很多研究,也没有找到解决该问题的方法。

you're not updating the sub-key, you're creating a global image key. 您没有更新子密钥,而是创建了全局image密钥。

Do that instead: 改为:

for x in item['image_result']:
   x['image'] = x.get('path')

if you want to extract a list of images (stored as a global images key) you just need to do: 如果要提取图像列表(存储为全局images键),则只需执行以下操作:

item['image'] = [x.get('path') for x in item['image_result']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM