I have the following code to print items from a dictionary.
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))
The above code works fine and prints the key and the values. Just out of curiosity I wanted to try
k,v = my_dict.items()
it gives me an error.I want to know why this is ? My understanding is that my_dict.items()
returns k and v
Best Answer
It returns a list of items (in python3 dict_items
object), that you cannot assign them to two variable. If you want to separately get the keys and values you can use dict.keys()
and dict.values()
attributes:
>>> 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]