[英]How to match keys in a dictionary with the elements in a list and store those key values to another dictionary in python?
[英]How to modify a list of key values in dictionary based on matches of another dictionary keys in python?
我有一本字典,
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}}
如果它的元素存在于字典 cond_dict 的键中,我想在这里填写 ex_dict 中的值列表。
例如:
在字典 ex_dict 中,有一个名为“recency”的键,它有一个包含 12 个元素的列表,这里有 3 个唯一元素,例如(当前、储蓄、固定)。
这三个元素应存在于字典 cond_dict 键中,如果此 dict 键中不存在任何元素,则其值应在与 ex_dict 关联的列表中添加为“RARE”。
这是一个示例 output:原始列表中的节省替换为 RARE,因为 cond_dict 的键中不存在节省。
'recency': ['current',
'RARE',
'fixed',
'current',
'RARE',
'fixed',
'current',
'fixed',
'fixed',
'fixed',
'current',
'fixed']
你能写下你的建议/答案吗?
for k,v in ex_dict.items():
ex_dict[k] = [item if item in cond_dict[k] else 'RARE' for item in v]
这是一种方法:
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)
尽管已经发布了答案,但我发布了相同的答案,因为我尝试过。 希望这会有所帮助并且很重要。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.