0
states = {state, abbr}
cities = {abbr, capital}

我想打印出state, abbr, capital3 个值或其他顺序。我尝试在以下状态下反转键值对:

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}

然后尝试使用(我不完全理解下面的代码)创建一个新的字典:

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错误。

请帮忙。还是我完全走错了路?谢谢。

4

1 回答 1

3

假设您的数据在字典中(不在您的示例代码中)。打印出您要查找的数据应该非常简单

for state, abbr in states.items():
   print('{0}, {1}, {2}'.format(state, abbr, cities[abbr]))
于 2012-10-26T17:50:06.980 回答