I've been having issues with adding values to already existing key values.
Here's my code:
mydict = {}
def assemble_dictionary(filename):
file = open(filename,'r')
for word in file:
word = word.strip().lower() #makes the word lower case and strips any unexpected chars
firstletter = word[0]
if firstletter in mydict.keys():
continue
else:
mydict[firstletter] = [word]
print(mydict)
assemble_dictionary('try.txt')
The try.txt
contains a couple of words - Ability
, Absolute
, Butterfly
, Cloud
. So Ability
and Absolute
should be under the same key, however I can't find a function that would enable me to do so. Something similar to
mydict[n].append(word)
where n would be the line number.
Furthermore is there a way to easily locate the number of value in dictionary?
Current Output =
{'a': ['ability'], 'b': ['butterfly'], 'c': ['cloud']}
but I want it to be
{'a': ['ability','absolute'], 'b': ['butterfly'], 'c': ['cloud']}
Option 1 :
you can put append statement when checking key is already exist in dict.
mydict = {}
def assemble_dictionary(filename):
file = open(filename,'r')
for word in file:
word = word.strip().lower() #makes the word lower case and strips any unexpected chars
firstletter = word[0]
if firstletter in mydict.keys():
mydict[firstletter].append(word)
else:
mydict[firstletter] = [word]
print(mydict)
option 2 : you can use dict setDefault to initialize the dict with default value in case key is not present then append the item.
mydict = {}
def assemble_dictionary(filename):
file = open(filename,'r')
for word in file:
word = word.strip().lower() #makes the word lower case and strips any unexpected chars
firstletter = word[0]
mydict.setdefault(firstletter,[]).append(word)
print(mydict)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments