【发布时间】:2020-09-13 13:41:07
【问题描述】:
我有两个要比较的字典,只有在所有值都匹配时才返回它们。其中一个字典是ordereddict,而另一个是常规的dict。因为我正在学习 python,所以我想我会使用csv 模块而不是pandas。 dictReader 返回了 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