definaly
definaly

Reputation: 154

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']}

Upvotes: 4

Views: 120

Answers (4)

Sach
Sach

Reputation: 912

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)

Upvotes: 4

Hemil Patel
Hemil Patel

Reputation: 319

You can achieve it this way

mydict = {}
a = ['apple', 'abc', 'b', 'c']
for word in a:
    word = word.strip().lower() #makes the word lower case and strips any unexpected chars
    firstletter = word[0]
    if firstletter in mydict.keys():
        values = mydict[firstletter] # Get the origial values/words 
        values.append(word) # Append new word to the list of words
        mydict[firstletter] = values
    else:
        mydict[firstletter] = [word]

print(mydict)

Outout :

{'a': ['apple', 'abc'], 'c': ['c'], 'b': ['b']}

Upvotes: 1

toti08
toti08

Reputation: 2454

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.

Upvotes: 2

Avichal Bettoli
Avichal Bettoli

Reputation: 79

mydict[firstletter] = [word], replaces the value

Since the key are in List format, try

mydict[firstletter].extend(word)

Upvotes: 0

Related Questions