gpt4 book ai didi

python - 比较两个字典并打印缺失或没有匹配项

转载 作者:行者123 更新时间:2023-12-01 08:50:44 27 4
gpt4 key购买 nike

我是 python 新手,真的很想在这里得到一些指导。

我有两个几乎相同的词典 - First_Dict 和 Second_Dict

First_Dict = {"Texas": ["San Antonio", "Austin", "Houston", "Dallas"], 
"California": ["San Diego", "Los Angeles", "San Francisco"],
"Florida": ["Miami", "Orlando", "Jacksonville", "Naples"],
"Arizona": ["Phoenix", "Tucson"]}


Second_Dict = {"Texas": ["San Antonio, Austin, Houston"],
"California": ["San Diego, Los Angeles, San Francisco"],
"Florida": ["Miami", "Orlando", "Jacksonville"], "Illinois":
["Chicago", "Naperville"]}

目标:我需要在以下流程中比较它们:

Compare keys
if key match
compare values
if all values match
break
else:
print the key and the corresponding missing value/s.
"Missing value/s on key "Florida" in the Second_Dict"
"Naples"

if keys NOT match or missing
print the unmatching/missing key and corresponding value/s.
"Missing key and value/s on First_Dict"
Illinois
Chicago
Naperville

"Missing key and value/s on Second_Dict"
Arizona
Phoenix
Tucson

到目前为止,我的代码并不多:) 抱歉,仍在学习。

for key, value in First_Dict.items() and Second_Dict.items():
if key in First_Dict.keys() == Second_Dict.keys():
for value in First_Dict.value() and Second_Dict.value :
if value in First_Dict.value() == Second_Dict.value():
break
else:
print(value)

最佳答案

我想您不仅想知道第一本词典与第二本词典的差异,而且还想知道第二本词典的差异。对我来说,一个好方法是按以下步骤分离控件:

  1. 查找两个字典的公共(public)键。
  2. 使用通用键计算两个词典中的值差异。
  3. 用相对值指示缺失的键。

可能的代码:

#Step 1
#Determination of common keys
first_keys = first_Dict.keys() #retrieve keys of the dictionary
second_keys = second_Dict.keys()
common_keys = [key for key in first_keys if key in second_keys]

#Step 2
#so now for common keys we look for differences in value and printing them
for common in common_keys:
townsA = first_Dict[common]
townsB = second_Dict[common]

#with the first statement determine the cities that are in the second
#dictionary but not in first one.
#with the second the opposite
missingOnFirst = [town for town in townsB if town not in townsA]
missingOnSecond = [town for town in townsA if town not in townsB]

if missingOnFirst:
print("Missing on {0} in first dictionary: \n\t{1}".format(common,"\n\t".join(missingOnFirst)))
if missingOnSecond:
print("Missing on {0} in second dictionary: \n\t{1}".format(common,"\n\t".join(missingOnSecond)))

#Step 3
#printing the missing keys:
#on First dictionary
print("\n")
print("Missing key and value/s on first dictionary")
for key in second_keys:
if key not in common_keys:
print("{0}:\n\t{1}".format(key,"\n\t".join(second_Dict[key])))
#on Second dictionary
print("Missing key and value/s on second dictionary")
for key in first_keys:
if key not in common_keys:
print("{0}:\n\t{1}".format(key,"\n\t".join(first_Dict[key])))

关于python - 比较两个字典并打印缺失或没有匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53143623/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com