2D Dictionaries
Remember that dictionaries are very similar to lists, except that they store data as key:value pairs. The value is what it's worth and the key is what it is called. The key is used to access the value, and keys are more meaningful than index numbers.
Dynamically Adding To A 2D Dictionary
This code dynamically adds to a 2D dictionary by starting with an empty dictionary and using an infinite loop to add user input.
clue = {}
while True:
name = input("Name: ")
location = input("Location: ")
weapon = input("Weapon: ")
clue[name] = {"location": location, "weapon":weapon} #line 7
print(clue)
output
Name: angshu
Location: burdwan
Weapon: hammer
{'angshu': {'location': 'burdwan', 'weapon': 'hammer'}}
The real magic happens on the 7th line of code. Instead of using .append() like we would with a list, we create a new dictionary entry.
The key is the name of the beast, but the value is a whole new dictionary that contains the details of the beast.
Each key:value pair in the dictionary is now a key that accesses a related dictionary
This example shows you how to add a prettyPrint() subroutine that works with a 2D dictionary.
clue = {}
def prettyPrint():
print()
for key, value in clue.items(): #This iterates over each key-value pair in the clue dictionary. Inside the loop
# moves along every 'key:subDictionary' pair and outputs the key (the name of the character).
print(key, end=": ")
for subKey, subValue in value.items(): #This nested loop iterates over each key-value pair in the nested dictionary associated with the current key
# (nested) `for` loop moves along every subkey and subvalue in each subDictionary.
print(subKey, subValue, end=" | ")
print()
while True:
name = input("Name: ")
location = input("Location: ")
weapon = input("Weapon: ")
clue[name] = {"location": location, "weapon":weapon}
prettyPrint()
john = {"daysCompleted": 46, "streak": 22}
janet = {"daysCompleted": 21, "streak": 21}
erica = {"daysCompleted": 75, "streak": 6}
courseProgress = {"John":john, "Janet":janet, "Erica":erica}
print(courseProgress)
print(courseProgress["Erica"])
# The bracket contains the key that references the sub dictionary.To access one item, I use two square brackets []. So to see only Erica's results, I would add this
No comments:
Post a Comment