繁体   English   中英

比较两个字典并打印出丢失或没有匹配项

[英]Compare two dictionaries and print out missing or no matches

我是 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. 查找两个字典的公共键。
  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])))

你可以这样做:

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"]}

for key, values in First_Dict.items():
    if key in Second_Dict:  # if key match
        diff = [value for value in values if value not in Second_Dict[key]]
        if not diff:  # all values match
            pass
        else:
            print("key: {}, missing values: {}".format(key, diff))
    else:
        print("key: {}, missing values: {}".format(key, values))

输出

key: Florida, missing values: ['Naples']
key: Texas, missing values: ['Dallas']
key: Arizona, missing values: ['Phoenix', 'Tucson']

diff = [value for value in values if value not in Second_Dict[key]]是一个列表First_Dict ,当键匹配时计算First_DictSecond_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"]}

for key, values in First_Dict.items():
    if key in Second_Dict:  # if key match
        diff_first = [value for value in values if value not in Second_Dict[key]]
        diff_second = [value for value in Second_Dict[key] if value not in values]
        if not diff_first:  # all values match
            pass
        else:
            print("key: {}, missing values: {} in Second_Dict".format(key, diff_first))

        if not diff_second:
            pass
        else:
            print("key: {}, missing values: {} in First_Dict".format(key, diff_second))
    else:
        print("key: {}, missing values: {} in Second_Dict".format(key, values))

for key, values in Second_Dict.items():
    if key not in First_Dict:
        print("key: {}, missing values: {} in First_Dict".format(key, values))

输出

key: Texas, missing values: ['Dallas'] in Second_Dict
key: Florida, missing values: ['Naples'] in Second_Dict
key: Arizona, missing values: ['Phoenix', 'Tucson'] in Second_Dict
key: Illinois, missing values: ['Chicago', 'Naperville'] in First_Dict

第二个循环用于迭代Second_Dict中缺少的First_Dict的键。

首先声明两个空列表,一个用于存储缺失的键,第二个用于该键的缺失值。

key_lst=[]
values_lst=[]

试试这个代码。

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","Dallas"],
       "California": ["San Diego", "Los Angeles", "San Francisco"],
       "Florida": ["Miami", "Orlando", "Jacksonville",], "Illinois": 
      ["Chicago", "Naperville"]}
key_lst=[]
values_lst=[]
for key, value in First_Dict.items() and Second_Dict.items():
    if key in First_Dict.keys() and Second_Dict.keys():
        if key in Second_Dict.keys() and First_Dict.keys() :
            continue
        else:
            key_lst.append(key)
    else:
        key_lst.append(key)
    if value in First_Dict.values() and Second_Dict.values():
        if value in Second_Dict.values() and First_Dict.values() :

            continue
        else:
            values_lst.append(value)
    else:
        values_lst.append(value)
for key, value in Second_Dict.items() and First_Dict.items():
    if key in First_Dict.keys() and Second_Dict.keys():
        if key in Second_Dict.keys() and First_Dict.keys() :
            continue
        else:
            key_lst.append(key)
    else:
        key_lst.append(key)
    if value in First_Dict.values() and Second_Dict.values():
        if value in Second_Dict.values() and First_Dict.values() :

            continue
        else:
            values_lst.append(value)
    else:
        values_lst.append(value)
print("Missing Keys: ",key_lst[0],": Missing Values",values_lst[0])
print("Missing Keys: ",key_lst[1],": Missing Values",values_lst[1])

输出是

Missing Keys:  Illinois : Missing Values ['Chicago', 'Naperville']
Missing Keys:  Arizona : Missing Values ['Phoenix', 'Tucson']

如果有帮助,请标记答案。

更多使用集合的一种选择:

mismatch = {}
missing_from_first = {}
missing_from_second = {}
for state in list(set([state for state in First_Dict] + [state for state in Second_Dict])):
  set1 = set(First_Dict.get(state, []))
  set2 = set(Second_Dict.get(state, []))
  mismatch[state] = list(set1.union(set2) - set1.intersection(set2))
  missing_from_first[state] = list(set2 - set1)
  missing_from_second[state] = list(set1 - set2)

所以,打印出结果:

print mismatch
print missing_from_first
print missing_from_second
#=> {'Florida': ['Naples'], 'Arizona': ['Tucson', 'Phoenix'], 'California': [], 'Texas': ['Dallas'], 'Illinois': ['Naperville', 'Chicago']}
#=> {'Florida': [], 'Arizona': [], 'California': [], 'Texas': [], 'Illinois': ['Naperville', 'Chicago']}
#=> {'Florida': ['Naples'], 'Arizona': ['Tucson', 'Phoenix'], 'California': [], 'Texas': ['Dallas'], 'Illinois': []}

迭代结果以按照您的意愿设置打印格式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM