Home > Software engineering >  Python: Appending all repeating index values to a dictionary
Python: Appending all repeating index values to a dictionary

Time:03-15

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. Something like:

    {'a': 0, 'b': 1,2 'c': 3, 'd': 4,5}

CodePudding user response:

If you want a key to have multiple values, use a list as the value:

d = {}
population = ['a','b','b','c','d','d']

for i, m in enumerate(population):
    d.setdefault(m, []).append(i)

Output:

{'a': [0], 'b': [1, 2], 'c': [3], 'd': [4, 5]}

CodePudding user response:

You could check if the key already exists and append if so. 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:

{'a': '0', 'b': '1,2', 'c': '3', 'd': '4,5'}
  • Related