【问题标题】:How do I print all values of a dictionary in order?如何按顺序打印字典的所有值?
【发布时间】:2021-09-15 23:37:06
【问题描述】:

我是菜鸟。总的来说,我对任何类型的计算机代码都有大约两周的经验。

我创建了一个字典,其中包含一些棒球运动员的姓名、他们的击球顺序和他们的位置。我试图让它打印在以“订单”、“名称”和“位置”为标题的列中,并在这些列下显示订单号、位置和名称。想想电子表格的布局(stackoverflow 不会让我在这里按我想要的方式格式化)。

订单名称位置 1 一个 Baddoo LF 2 J 舍普 1B 3 R 格罗斯曼 DH

I'm new here, so apparently you have to click the link to see what I wrote. Dodgy, I know...

如您所见,我已经尝试了 257 次才能让这个东西正常工作。我查阅了谷歌、python 书籍和其他资源,但均无济于事。

【问题讨论】:

标签: python dictionary printing


【解决方案1】:

这是工作代码

for order in lineup["order"]:
    order -= 1
    position = lineup["position"][order]
    name = lineup["name"][order ]
    print(order + 1, name, position)

您的字典包含 3 个列表 - 如果您想要条目 0,则必须分别访问每个列表中的条目 0。

这将是使用字典的一种更简单的方法

players = {1: ["LF", "A Baddoo"],
           2: ["1B", "J Schoop"]}
for player in players:
    print(players[player])

希望对你有帮助

【讨论】:

  • 是的,当我在 Spyder 中使用它时它可以工作,它看起来与我预想的完全一样,但是当我在 Jupyter 笔记本中运行它时出现错误,这是我们用于课堂的.奇怪的。它说 int 对象在您提供的第一行中不可调用。
  • 这是一个被代码调用的奇怪错误。我稍微更改了代码 - 尝试新代码,如果错误不断发生,您可以将“订单”重命名为其他名称。有关错误的更多信息,请阅读:careerkarma.com/blog/…
【解决方案2】:

Pandas 非常适合在您描述您正在尝试做的事情时创建表。您可以将字典转换为数据框/表。这里唯一的问题是行数需要相同的长度,在这种情况下它不是。 orderpositionname 列在列表中都有 9 个项目,而 pitcher 只有 1 个。所以我们可以做的是使用 pop 拉出 pitcher 键。这将为您留下一个仅包含上述 3 个列名称的字典,然后是一个列表,其中包含您的 pitcher 的 1 项。

import pandas as pd

lineup = {'order': [1,2,3,4,5,6,7,8,9],
          'position': ['LF', '1B', 'RF','DH','3B','SS','2B','C','CF'],
          'name': ['A Baddoo','J Schoop','R Grossman','M Cabrera','J Candelario', 'H Castro','W Castro','D Garneau','D Hill'],
          'pitcher':['Matt Manning']}


pitching = lineup.pop('pitcher')
starting_lineup = pd.DataFrame(lineup)

print("Today's Detroit Tigers starting lineup is: \n", starting_lineup.to_string(index=False), "\nPitcher: ", pitching[0])

输出:

Today's Detriot Tigers starting lineup is: 
  order position         name
     1       LF     A Baddoo
     2       1B     J Schoop
     3       RF   R Grossman
     4       DH    M Cabrera
     5       3B J Candelario
     6       SS     H Castro
     7       2B     W Castro
     8        C    D Garneau
     9       CF       D Hill 
Pitcher:  Matt Manning

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 2019-06-27
    • 2012-06-29
    相关资源
    最近更新 更多