Python:字典打印值而不是键

时间:2019-02-17 07:07:37

标签: python dictionary

这是我的代码:
if所在的行应做:比较Dict1Dict2的第一个,然后将打印dict是否较小的键的第一个 > value ,然后它将从该字典中删除第一个键和值。 请注意启动时的while循环。

它的作用
1.打印值,而不是键。 2.它打印的时间少了一些,而不是应打印的时间,即,如果dict 1有2个键,而dict2有3个键,它应该输出5行,但只输出4行。 随时帮助自己 Dict1 = {“ Player1”:46,“ Player2”:34} Dict2 = {“ Player3”:38,“ Player4”:55} 并应该输出* keys ** Player2然后Player3然后Player1然后Player4,每个都在自己的行中

 while Dict1 and Dict2:

     if Dict1.get(list(Dict1.keys())[0]) > Dict2.get(list(Dict2.keys())[0]):
         print(Dict2[list(Dict2.keys())[0]])
         del Dict2[list(Dict2.keys())[0]]
     elif Dict1.get(list(Dict1.keys())[0]) < Dict2.get(list(Dict2.keys())[0]):
         print(Dict1[list(Dict1.keys())[0]])
         del Dict1[list(Dict1.keys())[0]]

编辑:我从用户/马克·泰勒那里得到了帮助。 他告诉我这段代码:

for (key1, val1), (key2, val2) in zip(Dict1.items(), Dict2.items()):
    if val1 > val2:
      print(key2)
    elif val1 < val2:
      print(key1)

,但仅输出一次,并且应该输出Dict1和Dict2中的每个键 我应该做什么: 这是关于足球的。 Dict1的键是得分者的名字,其值在他们得分的那一刻。全部一支团队。 Dict2对于另一个团队来说是相同的。 我已经按其值对Dict1和Dict2进行了排序。 我需要输出在比赛中得分的球员(第一线得分第一,第二线得分第二的球员等等)

1 个答案:

答案 0 :(得分:1)

下面的将dict合并为元组排序列表的代码怎么样?

team1 = {"Player1": 46, "Player2": 34}
team2 = {"Player9": 89, "Player3": 38, "Player4": 55}

both_teams = [(k, v) for k, v in team1.items()]
both_teams.extend([(k, v) for k, v in team2.items()])
sorted_both_teams = sorted(both_teams, key=lambda x: x[1])
for entry in sorted_both_teams:
    print('Player {} scored at {}'.format(entry[0], entry[1]))

输出

Player Player2 scored at 34
Player Player3 scored at 38
Player Player1 scored at 46
Player Player4 scored at 55
Player Player9 scored at 89
相关问题