I am trying to map the keys of one dictionary to the keys of another dictionary to create a new dictionary. (The dictionaries are sorted in the order I want them to map up.)
For example:
Letter_Freq = {}
Letter_Freq2 = {'a':8,'b':6,'c':2}
Letter_Freq4 = {'e':24,'g':4,'f':3}
Wanted output:
{'a':'e', 'b':'g','c':'f'}
I've tried several things, but nothing works.
This is the closest I've gotten:
for key0 in Letter_Freq2:
for key1 in Letter_Freq4:
Letter_Freq[key0] = key1
This doesn't work. It just returns
{'a':'e', 'b':'e', 'c:'e'}
CodePudding user response:
Don't use nested loops when you want one-to-one mapping. Nested loops create a cross-product. And in this case, you repeatedly assign the same keys, and just get the final assignment.
Use zip()
to iterate over sequences in parallel. You don't need loops, you can simply pass this to the dict()
constructor:
Letter_Freq = dict(zip(Letter_Freq2, Letter_Freq4))
CodePudding user response:
Try
for k1, k2 in zip(Letter_Freq2, Letter_Freq4):
Letter_Freq[k1] = k2