如何获取包含字典的列表的值以与其他字典进行比较?

时间:2020-11-09 02:18:34

标签: python python-3.x

这是我的字典清单

scores = [{'names':'soccer', 'power':'5'},{'names':'football', 'power':6}]

如您所见,我可能在功效值中包含字符串。

如果分数值(足球)的名称等于我的字典,我想与之比较。

my_stats = {'soccer':3, 'football':2}

例如

for values in scores:
    if my_stats(index) == "soccer" and scores(names) == "soccer":
        if my_stats(value) < power(value):
            return power(value) is higher

我知道这段代码行不通,但这是我第一次尝试从列表中获取字典值。我猜我需要2 for循环吗?列表1个,字典1个?

3 个答案:

答案 0 :(得分:2)

我在scores列表中添加了一些条目,以使代码更加通用。

以下代码将扫描整个scores列表,并在my_stats中查找唯一游戏的最大值。

scores = [{'names':'soccer', 'power':'5'},
          {'names':'soccer', 'power':8},
          {'names':'football', 'power':6},
          {'names':'football', 'power':9}]
my_stats = {'soccer':3, 'football':2}

for score in scores:
    for game,power in my_stats.items():
        if score['names'] == game and int(score['power']) > power:
            my_stats[game] = int(score['power'])

print (my_stats)

其输出将是:

{'soccer': 8, 'football': 9}

原始scores列表的输出为:

{'soccer': 5, 'football': 6}

扩展代码

您可能还希望查看此选项。如果scores中的游戏不存在于my_stats中,则以下代码还将游戏添加到my_stats

scores = [{'names':'soccer', 'power':'5'},
          {'names':'soccer', 'power':8},
          {'names':'football', 'power':6},
          {'names':'football', 'power':9},
          {'names':'basketball', 'power':20}]
my_stats = {'soccer':3, 'football':2}

for score in scores:
    if score['names'] in my_stats:
        if int(score['power']) > my_stats[score['names']]:
            my_stats[score['names']] = int(score['power'])
    else:
        my_stats[score['names']] = int(score['power'])

    #for game,power in my_stats.items():
    #    if score['names'] == game and int(score['power']) > power:
    #        my_stats[game] = int(score['power'])

print (my_stats)

上面的代码将为您提供如下输出:

{'soccer': 8, 'football': 9, 'basketball': 20}

答案 1 :(得分:1)

for score in scores:
   if score['names'] == 'soccer':
      if score['power'] == my_stats['soccer']
        print('the name is soccer and the scores are even')

让我知道您是否正在尝试这样做! :)

注意:通常,如果您要比较字典,我建议保持字典键相同。我不确定您的目标是什么,但是例如,我将scores的结构更改为:

scores = {'power':
             {'football': 5, 'soccer': 6}
         }

这样您可以做到:

if scores['powers']['football'] == my_stats['football']:
    print('scores are the same')

答案 2 :(得分:1)

首先,您可以将scores标准化为与my_stats类似的数据结构。 可以这样完成:


>> _scores = dict(zip([item["names"] for item in a], [int(item["power"]) for item in a])
>> _scores
{'football': 6, 'soccer': 5}

然后像往常一样从字典中获取

>> _scores.get("soccer")
5