问题
I have a python dictionary which is some kind of a glossary.
glossary_dict = {'AA': 'AA_meaning',
'BB': 'BB_meaning',
'CC': 'CC_meaning',
}
Here is the original dictionary.
original = [{'AA': '299021.000000'},
{'BB': '299021.000000'},
{'CC': '131993.000000'},
]
I want to replace the keys of original
dictionary with the corresponding value of glossary_dict
.
The final result will look like this;
explained = {'AA_meaning': '299021.000000',
'BB_meaning': '299021.000000',
'CC_meaning': '131993.000000',
}
I want to solve this problem using dictionary comprehension approach. This is what I did;
explained = {glossary_dict[key]: value for (key, value) in original[0].items()}
The result is {'AA_meaning': '299021.000000'}
. It is close but still not the correct answer. What did I miss out?
I am using python 3.7
回答1:
You have a list of dict
s, Iterate the list and then access the key
Ex:
explained = {glossary_dict[key]: value for i in original for key, value in i.items()}
print(explained)
Output:
{'AA_meaning': '299021.000000',
'BB_meaning': '299021.000000',
'CC_meaning': '131993.000000'}
回答2:
Correct your explained
dictionary first. Then, use,
original = [{'AA': '299021.000000'},
{'BB': '299021.000000'},
{'CC': '131993.000000'},
]
to
original = {'AA': '299021.000000',
'BB': '299021.000000',
'CC': '131993.000000'}
Then,
explained = {glossary_dict[key]: value for (key, value) in original.items()}
来源:https://stackoverflow.com/questions/61906014/whats-wrong-with-this-dictionary-comprehension-code