Niraj Jayswal
Niraj Jayswal

Reputation: 1

How to print the 'key' of a dictionary without using loop or any keyword?

We can simply print the 'value' of a particular key in a dictionary. In the same way how can we print the 'key'?

For instance:

favorite_languages = {
 'jen': 'python',
 'sarah': 'c',
 'edward': 'ruby',
 'phil': 'python',
 }

We can easily print the values of their respective keys. Can't we print the keys separately?

Upvotes: 0

Views: 2051

Answers (2)

Ananth Krish
Ananth Krish

Reputation: 1

No, you can't print the keys alone for an instance without iterating. For value, we will know the key so by using a key we can easily locate a value but in the case of the key, we will not know how to locate the keys. Hence we need to iterate through keys with dictionary name(which contains starting address of the keys in the memory location).

Python also provides inbuild method to list all the keys i.e '.keys()'

In your case it will be favorite_languages.keys(),

Upvotes: 0

user9706
user9706

Reputation:

You can use the method keys() to extract he keys:

favorite_languages.keys()
['sarah', 'edward', 'jen', 'phil']

Upvotes: 1

Related Questions