Introduction
>>> my_dict = {'name': 'Kenneth'}
>>> my_dict
{'name': 'Kenneth'}
Key
Order of keys can change over time. This is why indexes have no use in dictionaries.
>>> my_dict = {'name': 'Kenneth', 'job': 'Teacher'}
>>> my_dict['job']
'Teacher'
>>> my_dict
{'job': 'Teacher', 'name': 'Kenneth'}
Dictionaries as Keys
>>> name_dict = {'names': {'first': 'Kenneth', 'last': 'Love'}}
>>> name_dict
{'name': {'last': 'Love', 'first': 'Kenneth'}}
>>> name_dict['names']
{'last': 'Love', 'first': 'Kenneth'}
>>> name_dict['names']['last']
'Love'
Tuples as Keys
Checking if a dungeon cell location (x,y) contains a monster or not, using Tuples.
>>> game_dict = {(2,2): True, (1,2): False}
>>> game_dict
{(2,2): True, (1,2): False}
>>> game_dict[(1,2)]
False
EXERCISE 1
List index VS. Dictionary key
def members(my_dict, my_list):
count = 0
for item in my_list:
for key in my_dict: ## key in my_dict
if key == item:
count += 1
return count
Create/Modify Key
>>> my_dict = {'name': 'Kenneth', 'job': 'Teacher'}
>>> my_dict['age'] = 33
>>> my_dict
{'name': 'Kenneth', 'job': 'Teacher', 'age': 33}
>>> my_dict['age'] = 34
>>> my_dict['age']
34
Process Multiple Keys
>>> my_dict = {'name': 'Kenneth', 'job': 'Teacher', 'age': 33}
>>> my_dict.update({'job': 'Teacher', 'state': 'Oregon', 'age': '33', 'name': 'Kenneth'})
>>> my_dict
{'job': 'Teacher', 'state': 'Oregon', 'age': '33', 'name': 'Kenneth'}
EXERCISE 2
Write a function that counts String items into a Dictionary
def word_count(my_string):
my_dict = {}
my_list = my_string.split()
for item in my_list:
if item not in my_dict:
my_dict.update({item: 1})
else:
my_dict[item] += 1
return my_dict
OUTPUT:
>>> print(word_count("i am that i am"))
{'am': 2, 'i': 2, 'that': 1}