来自现有字典值的新字典

new dictionary from existing dictionary values

我正在尝试弄清楚如何执行以下操作:

firstDictionary = {"firstKey" : "A", "secondKey" : "B"}
secondDictionary = {"firstKey" : 3, "secondKey" : 47}
emptyDictionary = {}

for key, value in firstDictionary, secondDictionary:
    # emptyDictionary = some sort of append method...

所以

secondDictionary = {"A" : 3, "B" : 47}

这很简单。您需要做的就是遍历其中一个字典项,并使用第一个字典中的键从本质上找到第二个字典的关联值。

>>> firstDictionary = {"firstKey" : "A", "secondKey" : "B"}
>>> secondDictionary = {"firstKey" : 3, "secondKey" : 47}
>>> emptyDictionary = {value : secondDictionary.get(key, None) for key, value in firstDictionary.items()}
>>> print emptyDictionary
{'A': 3, 'B': 47}

如果您确定两个词典具有相同的键,则将 dict.get 结构替换为词典索引

>>> {value : secondDictionary[key] for key, value in firstDictionary.items()}
{'A': 3, 'B': 47}