如果键已经存在,将值附加到键(python / jython) [英] Appending values to a key if key already exists (python/jython)

查看:126
本文介绍了如果键已经存在,将值附加到键(python / jython)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,我需要做一个字典。该列表具有重复(即将成为)具有不同值的键。如何找到这些密钥并附加新的值?

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

谢谢提前

解决方案

将您的字典列表中的值设置为:

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

等。即,您的一项目值是一项列表。这意味着当您有另一个'q'时,您可以执行以下操作:

  dictionary ['q']。append(5)

除了字典['q'] 将首次执行 KeyError ,所以使用 setdefault 替代:

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

所以现在你只需要遍历输入列表中的每个键,值对,并为每个键执行上述操作。



您可能还需要字典

  dictionary = collections.defaultdict(list)

所以你可以做字典['q']。append(5) - 它将与上述相同,在所有方面都是第一。如果您解析了原始列表并正确设置所有值后,您的字典如下所示:

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

您尝试执行 print(dictionary ['y'])。你期望发生什么?如果你使用正常的dict和 setdefault ,这被认为是一个错误,所以它会引发 KeyError 。如果您使用 defaultdict ,它将打印一个空列表。无论哪一个对您的代码来说都更有意义,应该确定您编码的方式。


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:

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.

这篇关于如果键已经存在,将值附加到键(python / jython)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆