作者:-不寻常- | 来源:互联网 | 2023-12-09 09:14
本文介绍了Python字典视图对象的示例和用法。通过对示例代码的解释,展示了字典视图对象的基本操作和特点。字典视图对象可以通过迭代或转换为列表来获取字典的键或值。同时,字典视图对象也是动态的,可以反映字典的变化。通过学习字典视图对象的用法,可以更好地理解和处理字典数据。
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)
那是因为您正在尝试访问字典视图对象(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,500]
>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['bacon','spam']
>>> # set operations
>>> keys & {'eggs','salad'}
{'bacon'}
>>> keys ^ {'sausage','juice'}
{'juice','spam'}
因此,基本上,您可以对其进行迭代(使用for key in RATES.keys()
循环,或仅使用print(list(RATES.keys()))
或print(list(RATES.values()))
将其转换为列表