如何根据python中另一个字典键的匹配来修改字典中的键值列表?

时间:2020-05-25 12:32:39

标签: python dictionary

我有一个字典,

ex_dict={'recency': ['current',
  'savings',
  'fixed',
  'current',
  'savings',
  'fixed',
  'current',
  'fixed',
  'fixed',
  'fixed',
  'current',
  'fixed'],
 'frequency': ['freq',
  'freq',
  'freq',
  'freq',
  'freq',
  'freq',
  'infreq',
  'freq',
  'freq',
  'freq',
  'infreq',
  'freq'],
 'money': ['med',
  'high',
  'high',
  'med',
  'high',
  'high',
  'low',
  'high',
  'md',
  'high',
  'high',
  'high']}

另一本词典,

cond_dict= {'recency': {'current': 0.33, 'fixed': 0.5},
           'frequency': {'freq': 0.83},
            'money': {'high': 0.67}}

在这里,我想在ex_dict的值列表中填写其元素是否存在于字典cond_dict的键中。

例如:

在字典ex_dict中,有一个名为“ recency”的键,它有一个包含12个元素的列表,这里有3个唯一元素,例如(当前,储蓄,固定)。

这三个元素应该存在于字典的cond_dict键中,如果该dict键中不存在任何一个元素,则其值应添加为与ex_dict关联的列表中的“ RARE”。

这是一个示例输出:原始清单中的节省被RARE替换,因为cond_dict关键字中不存在节省。

'recency': ['current',
  'RARE',
  'fixed',
  'current',
  'RARE',
  'fixed',
  'current',
  'fixed',
  'fixed',
  'fixed',
  'current',
  'fixed']

您能在上面写下您的建议/答案吗?

3 个答案:

答案 0 :(得分:1)

for k,v in ex_dict.items():
    ex_dict[k] = [item if item in cond_dict[k] else 'RARE' for item in v]

答案 1 :(得分:1)

这是一种方法:

for key in cond_dict:
        for k in ex_dict:
            if k == key:
                for ke in cond_dict[k]:
                    if ex_dict[k]:
                        a = ex_dict[k]
                        a.append('RARE')
                        ex_dict.update({k:a})
print(ex_dict)

答案 2 :(得分:1)

尽管已经对此发布了答案,但我还是尝试发布了相同的答案。希望这会有所帮助。

for i, v in ex_dict.items():            # loop through ex_dict
    check_list = cond_dict[i].keys()    # create a check_list to verify the values later
    for p, k in enumerate(v):           # loop through the values of ex_dict
        if k not in check_list:         # match each value with check_list
            v[p] = 'RARE'               # replace the unmatched value

print(ex_dict)                          # print result

如果您希望以更pythonic的方式使用它,这里是解决方法:)

res = {i: [k if k in cond_dict[i].keys() else "RARE" for k in v] for i, v in ex_dict.items()}    
print (res)
相关问题