Reputation: 123
I'm using Spyder 4.1.2 in window 10, I ran the lines of code below:
dict = {"Name": "Zara", "Age": 7}
print("Value: %s" % dict.keys())
I expected the output as a list:
['Name', 'Age']
But the output is
dict_keys(['Name', 'Age'])
Can anyone please tell me why? How do I fix it?
Upvotes: 0
Views: 440
Reputation: 972
Can anyone please tell me why?
In Python 3 dict.keys()
is returning a dict_keys
object which is actually a view object of that dict, and not a list
object. That is why you don't see it printed as a regular list.
From the official documentation:
The objects returned by
dict.keys()
,dict.values()
anddict.items()
are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.
Dictionary views can be iterated over to yield their respective data, and support membership tests [...]
How do I fix it?
You can directly cast the dict
into a list
, as answered here:
my_dict = {"Name": "Zara", "Age": 7}
print("Value: %s" % list(my_dict))
Note that I replaced dict
name with my_dict
. It is highly recommended to avoid shadowing names, specifically built in names as dict
.
Upvotes: 2
Reputation: 34136
You simply need to change your code to
dict = {"Name": "Zara", "Age": 7}
print("Value: %s" % list(dict.keys()))
Upvotes: 2