![](/img/trans.png)
[英]Where is the difference between iterating over a dictionary with list(dict.items()) and dict.items() in Python
[英]dict.items() in python dictionary return type
我有以下代码从字典中打印项目。
my_dict = {
"apples": 430,
"bananas": 312,
"oranges": 525,
"pears": 217,
"strawberries": 267,
"blueberry": 179,
"boysenberry": 432,
"blackberry": 266,
"apricot": 321,
"plum": 143,
"peaches": 154
}
for k, v in my_dict.items():
print('key {} value {}\n'.format(k, v))
上面的代码可以正常工作并打印键和值。 出于好奇,我想尝试
k,v = my_dict.items()
它给了我一个错误。我想知道为什么会这样吗? 我的理解是my_dict.items()
返回k and v
它返回一个项目列表(在python3 dict_items
对象中),您不能将它们分配给两个变量。 如果要分别获取键和值,则可以使用dict.keys()
和dict.values()
属性:
>>> my_dict.items()
[('bananas', 312), ('oranges', 525), ('peaches', 154), ('strawberries', 267), ('boysenberry', 432), ('apricot', 321), ('plum', 143), ('pears', 217), ('apples', 430), ('blueberry', 179), ('blackberry', 266)]
>>>
>>> k, v = my_dict.keys(), my_dict.values()
>>>
>>> k
['bananas', 'oranges', 'peaches', 'strawberries', 'boysenberry', 'apricot', 'plum', 'pears', 'apples', 'blueberry', 'blackberry']
>>>
>>> v
[312, 525, 154, 267, 432, 321, 143, 217, 430, 179, 266]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.