BTG123
BTG123

Reputation: 147

Nested Dicts in Python keys and values

I got a dict of dicts which looks like this:

d {
  1: {
    a: 'aaa',
    b: 'bbb',
    c: 'ccc'
  }
  2: {
    d: 'dddd',
    a: 'abc',
    c: 'cca'
  }
  3: {
    e: 'eee',
    a: 'ababa',
    b: 'bebebe'
  }
}

I want to convert by dict like this

d {
  a: 1,2,3
  b: 1,3
  c: 1,2
  d: 2
  e: 3
}

How can I achieve this?I tried reversing it but it throws unhashable dict.

Upvotes: 0

Views: 81

Answers (2)

user10307643
user10307643

Reputation:

a = {
    1: {
        "a": "aaa",
        "b": "bbb",
        "c": "ccc"
    },

    2: {
        "d": "ddd",
        "a": "abc",
        "c": "cca"
    },

    3: {
        "e": "eee",
        "a": "ababa",
        "b": "bebebe"
    }
}

from collections import defaultdict
b = defaultdict(list)
for i, v in a.items():
    for j in v:
        b[j].append(i)

The result b is:

defaultdict(<class 'list'>, {'a': [1, 2, 3], 'b': [1, 3], 'c': [1, 2], 'd': [2], 'e': [3]})

Upvotes: 2

Paritosh Singh
Paritosh Singh

Reputation: 6246

You just need to figure out the logic for it. Iterate through the main dictionary, and use the keys of the sub dictionaries to build your new dict.

d =  {
  1: {
    'a': 'aaa',
    'b': 'bbb',
    'c': 'ccc'
  },
  2: {
    'd': 'dddd',
    'a': 'abc',
    'c': 'cca'
  },
  3: {
    'e': 'eee',
    'a': 'ababa',
    'b': 'bebebe'
  }
}

newdict = {}
for k,v in d.items():
    for keys in v:
        newdict.setdefault(keys,[]).append(k)

print(newdict)

Upvotes: 2

Related Questions