Python dictionary basics

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.6

Check if a key exists

d = {"k1": "v1", "k2": "v2", "k3":"v3"}
if d.has_key("k1"):
  print "found"
found
Env: Python 2.7.6

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.6

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.6

get keys of dictionary

d = {"k1": "v1", "k2": "v2", "k3":"v3"}
print d.keys()
['k3', 'k2', 'k1']
Env: Python 2.7.6

get values of dictionary

d = {"k1": "v1", "k2": "v2", "k3":"v3"}
print d.values()
['v3', 'v2', 'v1']
Env: Python 2.7.6
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments