Bill Le
Bill Le

Reputation: 123

Unexpected output when printing dictionary keys

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

Answers (2)

alan.elkin
alan.elkin

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() and dict.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

Carlos Cordoba
Carlos Cordoba

Reputation: 34136

You simply need to change your code to

dict = {"Name": "Zara", "Age": 7}
print("Value: %s" % list(dict.keys()))

Upvotes: 2

Related Questions