Oct. 17, 2012

Python Dictionary Quick Guide

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

Please check out the “Dictionary” category for more articles about dictionaries. http://www.pythonforbeginners.com/category/dictionary/


# 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)

             

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.