无法将dict键与值匹配

时间:2015-10-26 20:03:46

标签: python html dictionary beautifulsoup html-parsing

尝试编写一个脚本,该脚本将(最终)在美国地图中用红色或蓝色着色,具体取决于该州的州长是共和党人还是民主党人。在我尝试对地图进行实际着色之前,我需要从dict'states'获取给定状态的'r'或'd'值。基本上,我无法将从stateid = (p['id'])返回的文本字符串与dict 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())

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

1 个答案:

答案 0 :(得分:4)

你不只是意味着:

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