试图写一个剧本,最终会在美国地图上涂上红色或蓝色,这取决于该州州长是共和党人还是民主党人。不过,在我尝试给地图上色之前,我需要从dict“states”中获取给定状态的“r”或“d”值。基本上,我无法将从stateid = (p['id'])返回的文本字符串与dictstates中同名键的值进行匹配。有谁能帮我弄清楚怎么做吗?

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 - 无法将dict键与值匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33354599/

10-11 14:14