states = {state, abbr}
cities = {abbr, capital}
我想打印出state, abbr, capital
或其他3个值的顺序。
我尝试使用以下状态反转键值对;
inv_states = {state: abbr for abbr, state in states.items()}
for abbr, capital in sorted(inv_states.items()):
print(abbr, ':', capital)
现在我有了:
states = {abbr, state}
cities = {abbr, capital}
然后尝试创建一个新的dict(我不完全理解下面的代码):
newDict = defaultdict(dict)
for abbr in (inv_states, cities):
for elem in abbr:
newDict[elem['index']].update(elem)
fullDict = newDict.values()
print(fullDict)
但我收到string indices must be intergers
错误。
请帮忙。还是我完全走错了路?感谢。
答案 0 :(得分:3)
假设您的数据在字典中(它不在您的示例代码中)。抛出你要查找的数据应该非常简单
for state, abbr in states.items():
print('{0}, {1}, {2}'.format(state, abbr, cities[abbr]))