
Python dictionary keys() - How to get all keys from a dictionary
The Python dictionary has keys()
method that returns all keys of it as a dict_keys object.
d = {'book': 24, 'pen': '5'}
keys = d.keys()
print(keys) # dict_keys(['book', 'pen'])
print(type(keys)) # <class 'dict_keys'>
for k in keys:
print(k)
# book
# pen
A dict_keys is an iterable, an object that can be iterated in the for loop. The following example shows how to get the dictionary keys as list.
d = {'book': 24, 'pen': '5'}
keys = d.keys()
a = list(keys)
print(keys) # dict_keys(['book', 'pen'])
print(a) # ['book', 'pen']
The relation of a dictionary and its keys
The dict_keys object is automatically updated by updating the dictionary. Its behavior is similar to the object referencing.
d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}
keys = d.keys()
d['VA'] = 'Virginia'
print(keys) # dict_keys(['CA', 'NV', 'TX', 'VA'])
keys
is the dictionary's keys and updated after updating the original dictionary.
Example
class User:
def __init__(self, name):
self.name = name
u = User(name='Josh')
d = u.__dict__
k = u.__dict__.keys()
print(d) # {'name': 'Josh'}
print(k) # dict_keys(['name'])
The __dict__
of an instance is the dictionary of properties. The instance's fields are the keys of its __dict__
.
Keys and values
There are similar methods in Python dictionary, values() and items().
d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}
keys = d.keys()
values = d.values()
items = d.items()
print(keys) # dict_keys(['CA', 'NV', 'TX'])
print(values) # dict_values(['California', 'Nevada', 'Texas'])
print(items) # dict_items([('CA', 'California'), ('NV', 'Nevada'), ('TX', 'Texas')])
keys()
returns the dictionary's keys, values()
returns its values, items()
returns its pairs each of which is a tuple of a key and value.
Comments
Powered by Markdown