Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding values to a dictionary key

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']}
like image 955
definaly Avatar asked Mar 06 '23 00:03

definaly


2 Answers

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)
like image 89
Sach Avatar answered Mar 07 '23 12:03

Sach


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.

like image 34
toti08 Avatar answered Mar 07 '23 13:03

toti08