根据其他两个字典中的匹配词创建字典-Python

时间:2019-03-20 16:49:17

标签: python

我正在尝试比较两个描述产品目录内容的大型词典。每本词典都由一个唯一的编码键和每个键的术语列表组成。

dict1 = {
"SKU001": ["Plumbing", "Pumps"], 
"SKU002": ["Motors"], 
"SKU003": ["Snow", "Blowers"], 
"SKU004": ["Pnuematic", "Hose", "Pumps"],
...
}

dict2 = {
"FAS001": ["Pnuematic", "Pumps"], 
"GRA001": ["Lawn", "Mowers"], 
"FAS002": ["Servo", "Motors"], 
"FAS003": ["Hose"], 
"GRA002": ["Snow", "Shovels"], 
"GRA003": ["Water", "Pumps"]
...
}

我想创建一个新字典,该字典从dict1借用键,并且其值是dict2的键列表,其中至少两个术语值匹配。理想的最终结果可能类似于:

match_dict = {
"SKU001": ["FAS001", "GRA003"], 
"SKU002": ["FAS002"], 
"SKU003": ["GRA002"], 
"SKU004": ["FAS001", "FAS003", "GRA003], 
...
}

我在创建此输出时遇到了问题。是否可以创建键列表并将其作为值分配给另一个键?我已经尝试过使用如下所示的嵌套循环,但是输出并没有达到期望,我不确定它是否可以正常工作。任何帮助表示赞赏!

matches = {}
for key, values in dict1.items():
    for value in values:
        if value in dict2.values():
            matches[key] = value
print(matches)

2 个答案:

答案 0 :(得分:2)

这是一种可能的实现方式:

dict1 = {
    "SKU001": ["Plumbing", "Pumps"], 
    "SKU002": ["Motors"], 
    "SKU003": ["Snow", "Blowers"], 
    "SKU004": ["Pnuematic", "Hose", "Pumps"],
}
dict2 = {
    "FAS001": ["Pnuematic", "Pumps"], 
    "GRA001": ["Lawn", "Mowers"], 
    "FAS002": ["Servo", "Motors"], 
    "FAS003": ["Hose"], 
    "GRA002": ["Snow", "Shovels"], 
    "GRA003": ["Water", "Pumps"]
}
match_dict_test = {
    "SKU001": ["FAS001", "GRA003"], 
    "SKU002": ["FAS002"], 
    "SKU003": ["GRA002"], 
    "SKU004": ["FAS001", "FAS003", "GRA003"], 
}

# Find keys for each item in dict2
dict2_reverse = {}
for k, v in dict2.items():
    for item in v:
        dict2_reverse.setdefault(item, []).append(k)
# Build dict of matches
match_dict = {}
for k, v in dict1.items():
    # Keys in dict2 associated to each item
    keys2 = (dict2_reverse.get(item, []) for item in v)
    # Save sorted list of keys from dict2 without repetitions
    match_dict[k] = sorted(set(k2i for k2 in keys2 for k2i in k2))
# Check result
print(match_dict == match_dict_test)
# True

答案 1 :(得分:0)

假设dict1和dict2可以有重复的值条目,则需要构建一个中间的多图字典,并且还要处理每个SKU的扩展值列表的唯一性:

public interface SpelInfo {
final int STARTAANTAL = 2;
final int MAXAANTALPUNTEN = 10;
final int INDEXNAAMDETAILS = 0;
final int INDEXGESLACHTDETAILS = 1;
final int INDEXPUNTENDETAILS = 2;
final int MINAANTALSPELERS = 3;
final int MAXAANTALSPELERS= 6;
final int EERSTESPELERINDEX = 0;
final int MAXLENGTHNAAM = 6;
final int MINLENGTHNAAM = 12;
final int AANTALSTAPELS = 2;
final char MAN = 'm';
final char VROUW = 'v';
final int SCHATKAART = 0;
final int KERKERKAART = 1;