Dictionaries in python
Interesting code found in some python Scrabble programs:
word = input("Enter a four letter word ") word = word.upper() letterNum = {'A':1,'E':1,'D':2,'R':2,'B':3,'M':3,'V':4,'Y':4,'J':8,'X':8}
What does the following line print?
print(letterNum['A'])
How was it used in the scrabble program?
One possible answer:
value = 0 for i in word: value += letterNum[i] print(value)
Another possible answer:
letterValue = [0,0,0,0] for i in range(4): letterValue[i] = letterNum[word[i]] print(letterValue)
Classwork:
Work in python’s shell and copy and paste your work on edmodo.com’s post: Dictionary – Clwk 1/8 – Basic Concepts
Create a dictionary: ‘hello’ is the key and ‘hola’ is the value
spanishDictionary = {'hello':'hola','goodbye':'adios','one':'uno','two':'dos'}
Access a value with the key
word = input("what word would like to translate to spanish? ") palabra = spanishDictionary[word]
Add a new key and value:
spanishDictionary.update({'blue':'azul'}) print(len(spanishDictionary))
Delete a key and the value:
del(spanishDictionary['blue'])
Replace the value of a key:
spanishDictionary['goodbye'] = 'chau'
Remove all items:
spanishDictionary.clear()
You can have a different type of value:
numbers = {'one':1,'two':2,'three':3,'four':4,'five':5} print( numbers['two'] * numbers['three'])
You can have a different type of key and a different type of value:
numbers = {90:0,91:1,92:2,93:3} print(numbers[92] * numbers[93])
Homework:
Add ten more words to the dictionary. Write a sentence in English and then translate it to Spanish or the language you chose. Add this new code to the original post.