编程语言
首页 > 编程语言> > 遍历python字典仅检索必需的行

遍历python字典仅检索必需的行

作者:互联网

我从外部来源获取HTML表格格式的数据-

from xml.etree import ElementTree as ET

s = """<table>
  <tr><th>Release</th><th>REFDB</th><th>URL</th></tr>
  <tr><td>3.7.3</td><td>12345</td><td>http://google.com</td></tr>
  <tr><td>3.7.4</td><td>456789</td><td>http://foo.com</td></tr>
</table>
"""

用于将html表转换为字典

table = ET.XML(s)
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
    values = [col.text for col in row]
    out = dict(zip(headers, values))

现在,由于我将通过命令行参数传递发布版本,因此我的预期输出如下.
$python myscript.py 3.7.3(我有一个代码)
我正在寻找一种解决方案,以在字典找到特定的发行版时遍历字典-在我的情况下为3.7.3

Release Version - 3.7.3
REFDB - 12345
URL - http://google.com

解决方法:

您不需要字典.只需解析每一行的内容,然后查看发行版本是否与您的输入匹配:

#coding:utf-8

import sys
from lxml import html

if len(sys.argv) != 2:
    raise Exception("Please provide release version only")

release_input = sys.argv[1].strip()

data = """<table>
  <tr><th>Release</th><th>REFDB</th><th>URL</th></tr>
  <tr><td>3.7.3</td><td>12345</td><td>http://google.com</td></tr>
  <tr><td>3.7.4</td><td>456789</td><td>http://foo.com</td></tr>
</table>
"""

tree = html.fromstring(data)
for row in tree.xpath('//tr')[1:]:
    release, refbd, url = row.xpath('.//td/text()')
    if release_input == release:
        print("Release Version - {}".format(release))
        print("REFBD - {}".format(refbd))
        print("URL - {}".format(url))
        break

print("{} release version wasn't found".format(release_input))

标签:ordereddictionary,python,list,dictionary,arraylist
来源: https://codeday.me/bug/20191013/1907496.html