【问题标题】:Comparing two dictionaries and return ONLY if all keys, values match比较两个字典并仅在所有键、值匹配时才返回
【发布时间】:2020-09-13 13:41:07
【问题描述】:

我有两个要比较的字典,只有在所有值都匹配时才返回它们。其中一个字典是ordereddict,而另一个是常规的dict。因为我正在学习 python,所以我想我会使用csv 模块而不是pandasdictReader 返回了 ordereddict。保证除了“name”之外的所有键都在两个字典中。

# Desired Result
odict_items([('name', 'Alice'), ('math', '87'), ('english', '81'), ('history', '74')])
odict_items([('name', 'Bob'), ('math', '87'), ('english', '85'), ('history', '87')])
odict_items([('name', 'Charlie'), ('math', '83'), ('english', '79'), ('history', '90')])
odict_items([('name', 'Dalia'), ('math', '91'), ('english', '70'), ('history', '81')])

personDict = {('math': 87), ('english': 81), ('history': 74)}

# returns "Alice"

这是我的代码,但它似乎是单独比较每个键值对。我试着玩弄集合和列表,但还是不明白。

for row in database:
    for key, value in row.items():
        if key in personDict and int(value) == personDict[key]:
            print(row["name"])
        else:
            print("No match")

它给了我类似的东西,至少我知道有些东西在起作用?

# Output
Alice
Alice
Alice
Alice
Charlie
No match
No match

【问题讨论】:

    标签: python-3.x dictionary


    【解决方案1】:

    您可以使用== 运算符来比较字典,这应该可以解决您的问题

    
    import itertools
    
    personDict = {'math': 87, 'english': 81, 'history': 74}
    row = {'name': 'Dalia', 'math': 87, 'english': 81, 'history': 74}
    
    if personDict == dict(itertools.islice(row.items(), 1, len(row))):
      print(row["name"])
    else:
      print("No Match")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多