Python dictionary (associative arrays) – some basic operations.
Initialize dictionary
d = {"k1": "v1", "k2": "v2", "k3":"v3"}
print d
print str(d){'k3': 'v3', 'k2': 'v2', 'k1': 'v1'}
{'k3': 'v3', 'k2': 'v2', 'k1': 'v1'}
Env: Python 2.7.18
Check if a key exists
d = {"k1": "v1", "k2": "v2", "k3":"v3"}
if d.has_key("k1"):
print "found"found
Env: Python 2.7.18
access value for a key
d = {"k1": "v1", "k2": "v2", "k3":"v3"}
if d.has_key("k1"):
print d["k1"]v1
Env: Python 2.7.18
list length/size using len()
len() return number of keys in dictionary. Note than len() can also be used to find array or string size.
d = {"k1": "v1", "k2": "v2", "k3":"v3"}
if d.has_key("k1"):
print len(d)3
Env: Python 2.7.18
get keys of dictionary
d = {"k1": "v1", "k2": "v2", "k3":"v3"}
print d.keys()['k3', 'k2', 'k1']
Env: Python 2.7.18
get values of dictionary
d = {"k1": "v1", "k2": "v2", "k3":"v3"}
print d.values()['v3', 'v2', 'v1']
Env: Python 2.7.18