'str'对象没有属性'get' - 如何告诉python返回的字符串是字典?

时间:2013-06-10 09:38:02

标签: python dictionary

当我尝试获取一个键的值时,我得到一个'str'对象没有属性'get'错误,而该值又是一个字典的名称。我怎么告诉python返回的字符串是字典?

choices = ['Country','State','Town']
chosen = 'Country'
country_color = {'Netherlands':'Red','Sweden':'Brown','Ukraine':'Yellow','China':'Pink','Japan':'Black'}
state_color = { .... }
town_color = { .... }

color_data = {'Country': ['col1','country_color'] ,'State': ['col2','state_color'] ,'Town': ['col3','town_color']}
    .....

color1 = lambda v: country_color.get(v['col1']) # this works
color2 = lambda v: country_color.get(v[color_data.get(chosen)[0]]) # this too works  
color3 = lambda v: color_data.get(chosen)[1].get(v[color_data.get(chosen)[0]]) # but this doesn't work; error - 'str' object has no attribute 'get'

    ....

2 个答案:

答案 0 :(得分:4)

color_data.get(chosen)[1]会返回country_color,这是一个字符串,如您所知。

如果您想访问country_color词典,为什么不更改color_data中的值:)?​​

color_data = {'Country': ['col1', country_color] # Notice how it's not a string anymore

答案 1 :(得分:0)

如果您这样编码:

  1. print("Client Name is : {}".format(function).get()) ---- 错误 ----
  2. 您将收到此错误“ str”对象没有属性“ get”
  3. print("Client Name is : {}".format(FNEntry.get())) ---- 固定 ----