0

At the moment I have two dictionaries I want to change the inner keys with the values of the other dictionary

d1 = {1:{1: 2.0,2: 1.5,3: 5.0},
      2:{1: 7.5,2: 6.0,3: 1.0}}
d2 = {1: 'a', 2: 'b', 3: 'c'}
expected output: {1:{'a': 2.0,'b': 1.5,'c': 5.0},
                  2:{'a': 7.5,'b': 6.0,'c': 1.0}}

Sadly these two dictionarys are filled with a lot of data and it takes a long time to iterate over d1 and call a method which iterates over d2 to replace the keys in d1.

Is it possible to change the inner key, value pair in a faster time? I found a possibility to replace the keys of a simple dictionary:

d = {'x':1,'y':2,'z':3}
d1 = {'x':'a','y':'b','z':'c'}
d = {d1[k]:v for k,v in d.items()}

output: {'a': 1, 'c': 3, 'b': 2}

but not with a nested dictionary.

So now I have no idea how I can solve my problem. Maybe one of you guys could help me please.

user1251007
  • 15,891
  • 14
  • 50
  • 76
pat92
  • 3
  • 3

2 Answers2

1

You may do it using nested dict comprehension as:

>>> d1 = {1:{1: 2.0,2: 1.5,3: 5.0},
...       2:{1: 7.5,2: 6.0,3: 1.0}}
>>> d2 = {1: 'a', 2: 'b', 3: 'c'}
>>> {a: {d2[k]: v for k, v in d.items()} for a, d in d1.items()}
{1: {'a': 2.0, 'c': 5.0, 'b': 1.5}, 2: {'a': 7.5, 'c': 1.0, 'b': 6.0}}

OR, using simple for loop as:

>>> for _, d in d1.items():  # Iterate over the "d1" dict
...     for k, v in d.items():  # Iterate in nested dict
...         d[d2[k]] = v  # Add new key based on value of "d2"
...         del d[k]   # Delete old key in nested dict
... 
>>> d1
{1: {'a': 2.0, 'c': 5.0, 'b': 1.5}, 2: {'a': 7.5, 'c': 1.0, 'b': 6.0}}

Second approach will update the original d1 dict, where as first approach will create the new dict object.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

I think the answer is to use dictionary zip which I've come across before.

Your question can be solved with zip as in this answer. Although yours requires an inner level so its slightly different.

Map two lists into a dictionary in Python

d1 = {1:{1: 2.0,2: 1.5,3: 5.0},
      2:{1: 7.5,2: 6.0,3: 1.0}}
d2 = {1: 'a', 2: 'b', 3: 'c'}

d1_edited = {} # I prefer to create a new dictionary than edit the existing whilst looping though existing
newKeys = d2.values() # e.g. ['a', 'b', 'c']
for outer in d1.keys(): # e.g. 1 on first iteration
    newValues = d1[outer]  # e.g. e.g. {1: 2.0,2: 1.5,3: 5.0} on first iteration
    newDict = dict(zip(newKeys,newValues)) # create dict as paired up keys and values
    d1_edited[outer] = newDict # assign dictionary to d1_edited using the unchanged outer key.

print d1_edited

output

{1: {'a': 1, 'c': 3, 'b': 2}, 2: {'a': 1, 'c': 3, 'b': 2}}
Community
  • 1
  • 1
Michael Currin
  • 615
  • 5
  • 14