Dictionaries: Examples

The code below will produce examples of almost everything you can do with a dictionary. The design here is for you to download and run this code in Idle, then be able to compare the results with the code. For many of us live examples are the best way to be able to understand.

# Dictionary examples: key:value
# Create and print a few dictionaries different ways
print("There are several ways to create a dictionary - hardest first")
print("Create a dictionary of color moods: ")
ColorMoods={'red':'passion', 'orange': 'energy', 'yellow':'positivity', 'green':'harmony', 'blue':'dependability', 'indigo':'uncertainty', 'purple':'luxury','white':'purity','black':'foreboding'}
print(ColorMoods)
# Now using the dict constructor
print("Create a list of arrival order to a party: ")
arvOrd=dict(Miles=1, Andrea=2, Courtney=3, Libby=4, Valerie=5, Meredith=6)
print (arvOrd)
# Now keys from a list
print("Create a dictionary from a list where all keys get the same value.")
print("You are not alone in thinking they screwed this one up, but here it is.")
KidsList1=['Bob','Carol','Ted','Alice']
age=10
KidsDict=dict.fromkeys(KidsList1,age)
print(KidsDict)
# Add one dictionary to another - add some kids, for example
KidsDict2={'Fred':16,'Sally':16}   # must be key/value pair
print("New kid dictionary: ", KidsDict2)
# ...and join them
KidsDict.update(KidsDict2)
print("Now KidsDict is "+str(KidsDict))
# Make a copy
KidsDict3=KidsDict2.copy()  #<-Note required parens
print("Copy of KidsDict2: ",str(KidsDict3))
# Clear all key/values but leave null dictionary defined
print("clear a dict")
KidsDict3.clear()   #<-Note required parens
print("KidsDict3 is now: "+ str(KidsDict3))
# Delete a key and value from a dictionay
print("Remove Bob from KidsDict")
del KidsDict['Bob']
print("Poof, all gone: "+str(KidsDict))
# Delete a dictionary entirely - KidsDict2 in this ex
print("Delete a dictionary")
del KidsDict2
try:
    print(KidsDict2)
except:
    print("Error occurs trying to access deleted dictionary")
# Change a value
print("Change a value, make Carol 18.")
KidsDict["Carol"]=18
print(KidsDict)
# Get a value
print("...or see it by itself")
print("Carol is ", KidsDict.get("Carol"))
# Membership "in" or "not in"
print("Alice is in the dictionary? ", ("Alice" in KidsDict))
# Elements in a dictionary
print("KidDict has this many members: ",str(len(KidsDict)))
print("KidsDict currently: ",KidsDict)
# The following now return "views" instead of "lists" (returned lists in 2.7)
# There were some fair memory/processing reasons for the change.
# To grab these values in a list use list(dictview)
print("Here are the 'views': ")
print("items: ", KidsDict.items())
print("keys: ", KidsDict.keys())
print("values: ", KidsDict.values())
print("Info from views moved into lists: ")
keylist=list(KidsDict.keys())
print("keylist: ",keylist)
valuelist=list(KidsDict.values())
print("valuelist: ", valuelist)
itemlist=list(KidsDict.items())
print("itemlist - a list of 2-tuple pairs: ", itemlist)
KidsDict3=KidsDict
print("KidsDict3 is recharged: ",KidsDict3)
# Remove a random item -- say what? Why?
print("Remove a random item - your challenge is find a reason.")
print("Our random item is: ", KidsDict3.popitem()) #no paramenters
print("and now KidsDict3 is: ", KidsDict3)
print("Remember a dictionary is NOT an ordered collection.")
# Set a known default then Remove a known item
KidsDict3.setdefault("John",12)
print(KidsDict3)
x=KidsDict3.pop("Carol")
print("Carol is: ",x)
x=KidsDict3.pop("Eddie","missing") #pop has a return value option if not found
print("Eddie is: ",x)
print("KidsDict3 is now: ",KidsDict3)
# Key Iteration
print("\nIteration examples: ")
v=iter(KidsDict3)
for item in range(0,len(KidsDict3)):
    tempkey=(next(v))
    print(tempkey, KidsDict3[tempkey])
print("\nAnother iteration example:")
myiter = iter(KidsDict)
myLam = lambda v1:v1+"  "+ str((KidsDict[v1]))
for kid in range(len(KidsDict)):
    print(myLam(next(myiter)))
xlist=list(KidsDict.keys())
print("xlist: ",xlist)