Get all keys in a Python dictionary
Get all keys in a dictionary
The keys method returns a list of all keys in the dictionary.
keys
method has the following syntax.
adict.keys()
return All keys in adict.
In Python 2.X, this returns a list. In Python 3.0, it returns an iterable view object.
params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
print params.keys()
# from w w w . j av a 2 s.c om
print params.values()
print params.items()
D = {'a': 1, 'b': 2, 'c': 3}
Ks = D.keys( ) # Unordered keys list
print Ks
Ks.sort( ) # Sorted keys list
print Ks
for key in Ks: # Iterate though sorted keys
print key, '=>', D[key]
for key in sorted(D):
print key, '=>', D[key]
The code above generates the following result.