Python Cheat Sheet: Dictionaries

Dictionaries are Python implementations of hash tables. They store arbitrary key-value associations, not restricted to a single data type. The dictionaries do not preserve order (no order between elements is defined) so there is no guarantee that any element enumeration will yield a certain order.

NB: unless otherwise specified, everything is Python 2 syntax.

Defining a dictionary:
D = { }
Initializing a dictionary:
D = dict( (i, False) for i in xrange(1, 11) if i % 2 == 0 )	#Python 2
D = { i : False for i in range(1, 11) if i % 2 == 0 }		#Python 3

Note: this syntax is also known as dictionary comprehension.

Enumerating all the items in a dictionary:
for i in D:
	print i, D[i]	#key, value

…or:

for k, v in D.iteritems():
	print k, v	#key, value
Looking up an element:
if k in D:
	print k 
Adding elements:
D[key] = value

Note: no error is thrown if the element already exists; an overwrite happens.

Removing elements:
del D[key]
Using a dictionary as a lookup table to remove duplicates in a list:
D = {}
for i in L:
	if i in D:
  		del L[i]
  	else:
  		D[i] = True

Note: a set data type is more suited for such task. There is also a simplified syntax (e.g. list(set(L)) ) that can be used if the element order within the input list does not need to be preserved.

That’s it for today, thank you for your read!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.