简体   繁体   中英

How do I make a list of tuples into a dictionary without overwriting already existing keys?

I am new to python, and I'm having trouble with my coding.

I have a large text, where every word in this text has gotten a tag (to witch part of speech the words belong).

The tuple looks something like this:

tuple1=[(bag, NN), (run, VB), (window, NN), (act, NN), (act,VB)]

And as you see, the word "act" can be both a verb and a noun. So when I want to make this tuple into a dictionary, I want both {act:NN, act:VB}. I have not managed to do this without overwriting the already existing key.

This is what I have so far:

dicts={}
for i in tuple1:
    dicts[i[0]]=i[1]

ALSO: How can I make every word into either small letters or big letters? So that there is no difference between for example "The" and "the"?

Thanks!

dicts = {}
for key, value in data:
    dicts.setdefault(key,[]).append(value)

returns:

{'bag': ['NN'], 'run': ['VB'], 'window': ['NN'], 'act': ['NN', 'VB']}
dict1 = {}
tuple1 = ((<word>, <type>), ...)

for k, v in tuple1:
    if k in dict1 and v in dict1[k]:
        continue
    elif k not in dict1:
        dict1[k] = [v]
    elif v not in dict1[k]:
        dict1[k].append(v)

Tested with:

(('bag', 'noun'), ('run', 'verb'), ('run', 'noun'), ('act', 'noun'), ('act', 'verb'))

And given output is:

{'bag': ['noun'], 'run': ['verb', 'noun'], 'act': ['noun', 'verb']}

My general idea was that you could simply assign a key to a list which contains the type of word it is and therefore it'd remove any need for adding additional keys with a prefix verb_ or noun_ etc.

On your latter question, to convert a word (string) into either upper or lowercase simply call str.lower() to turn "Hello, world!" into "hello, world!" and str.upper() to turn "hello, world!" into "HELLO, WORLD!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM