Python Dictionary Quick Guide

As the title says, this is a Python dictionary quick guide.

Please check out the Dictionary Tutorial for more articles about dictionaries.

Python Dictionary Quick Guide

# key/value pairs declaration
 dict = {

#Get all keys

#Get all values

 dict['key2'] = ‘value8′

 print dict['key1']

# prints ‘value2′
 print dict['key2']

# empty declaration + assignment of key-value pair
 emptyDict = {}

# looping through dictionaries (keys and values)
 for key in dict:
 print dict[key]

# sorting keys and accessing their value in order
 keys = dict.keys()
 for key in keys:
 print dict[key]

# looping their values directory (not in order)
 for value in dict.values():
 print value

# getting both the keys and values at once
 for key,value in dict.items():
 print “%s=%s” % (key,value)

# deleting an entry
 del dict['key2']

# delete all entries in a dictionary

# size of the dictionary


Leave a Reply

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