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

时间:2018-11-04 17:43:34

标签: python dictionary

我是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)

4 个答案:

答案 0 :(得分:1)

我想您不仅想知道第一本字典与第二本字典的区别,反之亦然。 对我来说,一个好方法是按照以下步骤分离控件:

  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])))

答案 1 :(得分:0)

您可以执行以下操作:

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]]行是list comprehension,当键匹配时,计算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中的键。

答案 2 :(得分:0)

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

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']

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

答案 3 :(得分:0)

一组使用选项的更多选择:

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': []}

遍历结果以按需格式化打印。