【发布时间】:2012-10-26 17:47:14
【问题描述】:
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}
然后尝试使用(我不完全理解下面的代码)创建一个新的字典:
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 错误。
请帮忙。还是我完全走错了路?谢谢。
【问题讨论】:
-
我在这里有点困惑。你想做什么?
-
{state, abbr},这是一个集合,不是字典。 -
请在保存编辑之前查看问题的外观。
-
@squigglytail.. 你刚刚重新编辑过你的帖子吗?我出于某种原因对其进行了编辑。您的代码应该在
code tags中,您可以通过在代码前添加4 spaces来添加。
标签: python python-3.x python-3.1