Search code examples
pythondictionarydefaultdict

How to get a dict of the keys for all values in another dict


I am trying to iterate over a dictionary with multiple values for same index to account for repeating values.

a = []
for x,y in new2.items():
    a[y].append(x)
print(a)

I have tried many approaches please help me identify the possible error.

The input file is like: {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6, ...}

The output should be: {1: [0, 1], 2: [2, 3, 4], 6: [5, 6, 7], 7: [8, 9], 12: [10], 14: [11, 12], 15: [15, 16]}


Solution

  • Looks like you have to initialize a to a defaultdict, not to a list

    >>> from collections import defaultdict
    >>> new2 = {'caseid': {0: 1, 1: 1, 2: 2, 3: 2, 4: 2, 5: 6}}
    >>> a = defaultdict(list)
    >>> for x,y in new2['caseid'].items():
    ...     a[y].append(x)
    ... 
    >>> print(a)
    defaultdict(<class 'list'>, {1: [0, 1], 2: [2, 3, 4], 6: [5]})
    >>> print(dict(a))
    {1: [0, 1], 2: [2, 3, 4], 6: [5]}