我有词典,其中包含不同的列表。
我想将数据合并到不同的字典中,并在其中附加类似键的值。
{'mental_issue': ['stress', 'live in fear', 'stomach curl', 'wracked by stress', 'chest tighten']}
{'sexual_abuse': ['stalking'], 'mental_issue': ['abuse', 'pica']}
{}
{'verbal_abuse': ['in the face'], 'mental_issue': ['abuse']}
{}
{'mental_issue': ['abuse']}
{'mental_issue': ['abuse']}
{'mental_abuse': ['name call'], 'mental_issue': ['abuse']}
{}
{'mental_issue': ['broken jaw', 'abuse', 'heart broken']}
{'mental_issue': ['live in fear']}
{'mental_issue': ['abuse', 'trauma']}
{'mental_issue': ['nightmares', 'abuse', 'panic attack']}
{'mental_issue': ['stress']}
{'mental_issue': ['severe']}
{'mental_issue': ['nightmares', 'bad emotional state']}
{'sexual_abuse': ['rape'], 'mental_issue': ['stress', 'paranoia']}
{'mental_issue': ['fracturing both my', 'both my knees']}
{'mental_issue': ['abuse']}
{'sexual_abuse': ['rape'], 'verbal_abuse': ['kicking'], 'mental_issue': ['nightmares']}
我想合并所有问题的值,例如mental_abuse
应该使所有字典都具有智力上的优势。
我写了这个逻辑-
sexual_abuse_list = []
d = {'sexual_abuse': ['rape'], 'verbal_abuse': ['kicking'], 'mental_issue': ['nightmares']}
if 'sexual_abuse' in d:
for item in d['sexual_abuse']:
sexual_abuse_list.append(item)
这是正确的逻辑吗?还是可以编写更好的逻辑?
答案 0 :(得分:5)
使用collections.defaultdict
例如:
from collections import defaultdict
lst = [{'mental_issue': ['stress', 'live in fear', 'stomach curl', 'wracked by stress', 'chest tighten']},
{'sexual_abuse': ['stalking'], 'mental_issue': ['abuse', 'pica']},
{},
{'verbal_abuse': ['in the face'], 'mental_issue': ['abuse']},
{},
{'mental_issue': ['abuse']},
{'mental_issue': ['abuse']},
{'mental_abuse': ['name call'], 'mental_issue': ['abuse']},
{},
{'mental_issue': ['broken jaw', 'abuse', 'heart broken']},
{'mental_issue': ['live in fear']},
{'mental_issue': ['abuse', 'trauma']},
{'mental_issue': ['nightmares', 'abuse', 'panic attack']},
{'mental_issue': ['stress']},
{'mental_issue': ['severe']},
{'mental_issue': ['nightmares', 'bad emotional state']},
{'sexual_abuse': ['rape'], 'mental_issue': ['stress', 'paranoia']},
{'mental_issue': ['fracturing both my', 'both my knees']},
{'mental_issue': ['abuse']},
{'sexual_abuse': ['rape'], 'verbal_abuse': ['kicking'], 'mental_issue': ['nightmares']}]
d = defaultdict(list)
for i in lst:
for k, v in i.items():
d[k].extend(v)
print(d)
输出:
defaultdict(<type 'list'>, {'sexual_abuse': ['stalking', 'rape', 'rape'], 'verbal_abuse': ['in the face', 'kicking'], 'mental_abuse': ['name call'], 'mental_issue': ['stress', 'live in fear', 'stomach curl', 'wracked by stress', 'chest tighten', 'abuse', 'pica', 'abuse', 'abuse', 'abuse', 'abuse', 'broken jaw', 'abuse', 'heart broken', 'live in fear', 'abuse', 'trauma', 'nightmares', 'abuse', 'panic attack', 'stress', 'severe', 'nightmares', 'bad emotional state', 'stress', 'paranoia', 'fracturing both my', 'both my knees', 'abuse', 'nightmares']})