Appending values to a key if key already exists (p

2020-07-22 19:52发布

问题:

I have a list that I need to make into a dictionary. The list has duplicate (soon to be) keys which have different values. How do I find these keys and append the new values to it?

list=[q:1,w:2,q:7]
dictionary= q:1,7
            w:2

Thanks in advance

回答1:

Make the values in your dictionary lists, so that you have:

dictionary = {'q': [1, 7],
              'w': [2]
}

etc. ie, your one-item values are one-item lists. This means when you have another 'q', you can do this:

dictionary['q'].append(5)

Except that dictionary['q'] will be a KeyError the first time you do it, so use setdefault instead:

dictionary.setdefault('q', []).append(5)

So now you just need to iterate over every key,value pair in the input list and do the above for each of them.

You might alternatively want to have dictionary be:

dictionary = collections.defaultdict(list)

So you can just do dictionary['q'].append(5) - and it will work the same as the above, in all respects bar one. If, after you have parsed your original list and set all the values properly, your dictionary looks like this:

dictionary = {'q': [1, 7, 5]
              'w': [2, 8, 10, 80]
              'x': [3]
}

And you try to do print(dictionary['y']). What do you expect to happen? If you use a normal dict and setdefault, this is considered an error, and so it will raise KeyError. If you use a defaultdict, it will print an empty list. Whichever of these makes more sense for your code should determine which way you code it.