python - 字典键与值匹配时遇到问题

标签 python html dictionary beautifulsoup html-parsing

尝试编写一个脚本,该脚本(最终)根据该州州长是共和党还是民主党,将美国 map 涂成红色或蓝色。在我尝试实际为 map 着色之前,我需要从字典“states”中获取给定状态的“r”或“d”值。基本上,我无法将从 stateid = (p['id']) 返回的文本字符串与字典 states< 中同名键的值进行匹配。/。谁能帮我弄清楚如何做到这一点?

import BeautifulSoup

states = {'AL':'r', 'AK':'d', 'AZ':'r', 'AR':'r', 'CA':'d', 'CO':'d', 'CT':'d','DE':'d','FL':'r','GA':'r','HI':'d','ID':'r','IL':'r','IN':'r','IO':'r','KA':'r','KY':'d','LA':'r','ME':'r','MD':'r','MA':'r','MI':'r','MN':'d','MS':'r','MO':'d','MT':'d','NE':'r','NH':'d','NJ':'r','NM':'r','NY':'d','NC':'r','ND':'r','OH':'r','OK':'r','OR':'d','PA':'d','RI':'d','SC':'r','SD':'r','TE':'r','TX':'r','UT':'r','VT':'d','VA':'d','WA':'d','WV':'d','WI':'r','WY':'r'}

svg = open('blankmap.svg', 'r').read()

soup = BeautifulSoup(svg, "lxml")

paths = soup.find_all('path')
for p in paths:
    stateid = (p['id'])
    if stateid in states:
        print([stateid].values())

您可以在最后一行看到我(失败的)尝试完成此任务。

最佳答案

你的意思是不是:

if stateid in states:
    print(states[stateid])

关于python - 字典键与值匹配时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33354599/

相关文章:

python - 带有 NaN 键的字典到 pandas 系列

python - 绘制 DataFrame 字典

python - 在 iOS 应用程序中运行 python 脚本

javascript - 获取html标签的大小

python - pandas:如何获取 .to_string() 方法以将列标题与列值对齐?

html - 扩展 html5 微数据事件模式

javascript - 手机和平板电脑的悬停问题

python - 按照 python3 的顺序移动字典中的键

python - 从setuptools迁移到pip + virtualenv

python - 将 Qt Pyside2 与 asyncio await 语法一起使用?