[英]Python: Appending all repeating index values to a dictionary
I want a dictionary that appends ALL indexes as values that have the same key我想要一个将所有索引附加为具有相同键的值的字典
d = dict()
population = ['a','b','b','c','d','d']
for _, m in enumerate(population):
d[m] = _
*output*
{'a': 0, 'b': 2, 'c': 3, 'd': 5}
However, this only outputs the last index found of the keys.但是,这只会输出找到的键的最后一个索引。 I want it to append ALL index values as values to the key.我希望它以 append ALL 索引值作为键的值。 Something like:就像是:
{'a': 0, 'b': 1,2 'c': 3, 'd': 4,5}
You could check if the key already exists and append if so.您可以检查密钥是否已存在,如果存在,则为 append。 Else add _
as new value否则添加_
作为新值
d = dict()
population = ['a','b','b','c','d','d']
for _, m in enumerate(population):
if m in d:
d[m] = d[m] +',' + str(_)
else:
d[m] = str(_)
print(d)
Output: Output:
{'a': '0', 'b': '1,2', 'c': '3', 'd': '4,5'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.