python - 如何在 Forloop 中的 Python 中将字符串附加到字典
问题描述
我需要将字符串的值附加到forloop中python字典中的特定键,如果forloop中的数据为空,则给出我无法正确获取的空字符串的值,这是一些代码,
top100 = {}
for product in product_list:
title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
price = product.xpath('div[@class="someClass"]/text()') # LIST of 100
# the value in the title is list of 100 title
# more like ['title1', 'title2', ...] and so the price [100, 230, ...]
# how to append each pairs of title and price so i have list of dictionary
top100['title'].append(title)
top100['price'].append(price)
print( top100)
输出:
KeyError: 'title'
但我需要更多类似的东西:
top100 = [{'title': 'title1', 'price': 'price1'},
{'title': 'title2', 'price': 'price2'}
]
解决方案
top 100
变量应该是一个列表,然后附加一个字典
top100 = []
for product in product_list:
title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
price = product.xpath('div[@class="someClass"]/text()') # LIST of 100
top100.append({'title':title,'price':price})
print( top100)
推荐阅读
- c++ - 使用 fdopen 的正确方法
- vb.net - 当输入的大小可能发生变化时如何修改文本文件的一部分
- blueprism - 无法加载无法识别的应用程序类型浏览器启动
- tcp - Sim7080G 模块在使用 GNSS 时无法通过 TCP 发送数据
- windows - windows/delphi 中的 Alpha 3 语言扩展从哪里获取?
- swift - 如何快速删除滚动视图侧边栏
- c - 哪种方法更适合在 C 中的循环中递增和遍历
- java - 调用 CRUD 存储库时 Spring AutoWire 不起作用
- python - 将 python 脚本与 HTML 输入页面链接
- python - 为什么单独线程中的“face_recognition”包会减慢 UI 线程?