I have a dictionary
Dict = {'ALice':1, 'in':2, 'Wonderland':3}
I could find ways to return key values but there was no way to return key names.
I want Python to return the dictionary key names step by step (for loop) for example:
Alice
in
Wonderland
To enumerate both keys and values, we can use the dictionary items() method. The items() method returns an object with the key-value pairs as tuples. The following example shows how we can use the items() method with the enumerate() function and access both the key and its corresponding value.
Python allows you to enumerate both keys and values of a dictionary.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
To print the dictionary keys in Python, use the dict. keys() method to get the keys and then use the print() function to print those keys. The dict. keys() method returns a view object that displays a list of all the keys in the dictionary.
You can use .keys()
:
for key in your_dict.keys():
print key
or just iterate over the dictionary:
for key in your_dict:
print key
Do note that dictionaries aren't ordered. Your resulting keys will come out in a somewhat random order:
['Wonderland', 'ALice', 'in']
If you care about order, a solution would be to use lists, which are ordered:
sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)]
for key, value in sort_of_dict:
print key
Now you get your desired results:
>>> sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)]
>>>
>>> for key, value in sort_of_dict:
... print key
...
ALice
in
Wonderland
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With