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
Make the values in your dictionary lists, so that you have:
etc. ie, your one-item values are one-item lists. This means when you have another
'q'
, you can do this:Except that
dictionary['q']
will be aKeyError
the first time you do it, so usesetdefault
instead: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: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:And you try to do
print(dictionary['y'])
. What do you expect to happen? If you use a normal dict andsetdefault
, this is considered an error, and so it will raiseKeyError
. If you use adefaultdict
, it will print an empty list. Whichever of these makes more sense for your code should determine which way you code it.