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)
You could simply append your word to the existing key:
def assemble_dictionary(filename):
with open(filename,'r') as f:
for word in f:
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]
Output:
{'a': ['ability', 'absolute'], 'b': ['butterfly'], 'c': ['cloud']}
Also (not related to the question) it's better to use the with
statement to open your file, that will also close it once you're done working with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With