【问题标题】:Printing from two dictionaries从两个字典打印
【发布时间】: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


【解决方案1】:

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

for state, abbr in states.items():
   print('{0}, {1}, {2}'.format(state, abbr, cities[abbr]))

【讨论】:

  • 这在 Python 3.1 中不起作用(正如问题标题所要求的那样); print 应该是一个函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
相关资源
最近更新 更多