Search code examples
pythonpython-3.xdictionarydefaultdict

Duplicate key in dictionary from list


I have a list which provides the values to a dictionary. However, the key is duplicated, so as a result just the last value is kept in the dictionary.

As an example, I have the following:

word='HOUSE'
classification=['NOUN','VERB']
dictionary= {}

for element in classification:
    dictionary= {
                 'word':word,
                 'classification':element
                 }

This code just is keeping this entrance:

{'word': 'HOUSE', 'classification': 'VERB'}

How can I get classification NOUN? I have tried defaultdict, but I have not been able to make it work:

data_dict = defaultdict(list)

for element in classification:
    dictionary[word].append(word)
    dictionary[classification].append(element)

Thanks for your help


Solution

  • The key on the lists must be unique. So when you try to give more than one value to the same key, it keeps the last value. Maybe you can match the key with a list. For example.

    word='HOUSE'
    classification=['NOUN','VERB']
    dictionary= {}
    
    dictionary['word'] = word
    dictionary['classification'] = classification
    

    the output is as follows

    >>>print(dictionary)
    >>>{'word': 'HOUSE', 'classification': ['NOUN', 'VERB']}
    

    if you need any element

    >>>dictionary['classification'][0]
    >>>'NOUN'