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 = {
 ‘key1′:’value1′,
 ‘key2′:’value2′,
 ‘key3′:’value3′
 }

#Get all keys
 dict.keys()

#Get all values
 dict.values()

#Modifying
 dict['key2'] = ‘value8′

#Accessing
 print dict['key1']

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

# empty declaration + assignment of key-value pair
 emptyDict = {}
 emptyDict['key4']=’value4′

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

# sorting keys and accessing their value in order
 keys = dict.keys()
 keys.sort()
 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
 dict.clear()

# size of the dictionary
 len(dict)

 

Leave a Reply

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