Appending values to a key if key already exists (python/jython)

浪尽此生 提交于 2019-12-04 14:23:24

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!