有没有一种方法可以在python 3.8中访问这些Rates而不出现TypeError:'dict_keys'对象不可下标?

时间:2019-12-11 12:49:33

标签: python dictionary

RATES = {
        "Australian Dollar":1.4099,
        "Brazilian Real":3.7927,
        "Canadian dollar":1.3375,
        "Switzerland Franc":0.9964,
        "China Yuan":6.7131,
        "Euro":0.8845,
        "United Kingdom Pound":0.763,
        "Hungarian Forint":279.337,
        "Indian Rupees":68.98,
        "Japanese Yen":110.5194,
        "Kenyan shilling":100.6989,
        "Korean Won":1133.5973,
        "Malawian Kwacha":723.985,
        "New Zealand dollar":1.4558,
        "Oman Riyal":0.385,
        "Tanzanian Shilling":2344.103,
        "Ugandan Shilling":3708.5025,
        "United States Dollar":1,
        "South African Rand":14.3397,
        "Zambian Kwacha":12.029
        }

变量= tk.StringVar() variable.set(无)

self.opt = tk.OptionMenu(self.frame,变量,* RATES,凸纹='凸起',bd = 2,宽度= 8,bg ='#008085') self.opt.grid(第2行,第2列,padx = 10,pady = 10)

1 个答案:

答案 0 :(得分:0)

那是因为您正在尝试访问字典视图对象(https://docs.python.org/3.8/library/stdtypes.html#dictionary-view-objects

Python文档网站上的一些示例

>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.keys()
>>> values = dishes.values()

>>> # iteration
>>> n = 0
>>> for val in values:
...     n += val
>>> print(n)
504

>>> # keys and values are iterated over in the same order (insertion order)
>>> list(keys)
['eggs', 'sausage', 'bacon', 'spam']
>>> list(values)
[2, 1, 1, 500]

>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['bacon', 'spam']

>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}
>>> keys ^ {'sausage', 'juice'}
{'juice', 'sausage', 'bacon', 'spam'}

因此,基本上,您可以对其进行迭代(使用for key in RATES.keys()循环,或仅使用print(list(RATES.keys()))print(list(RATES.values()))将其转换为列表