我有一个像这样的Dict文件:
"asks": 2,
"Hey": 1,
"I": 2,
"Jim": 3,
"Like": 4,
"Love": 1,
"she": 1,
"You": 2
我想操作值的键== 1到"False"然后把它们加起来得到一个新的值。所以我的Final Dict应该是这样的:
"asks": 2,
"False": 3,
"I": 2,
"Jim": 3,
"Like": 4,
"You": 2
一种方法:
d = {"asks": 2, "Hey": 1, "I": 2, "Jim": 3, "Like": 4, "Love": 1, "she": 1, "You": 2}
res = {}
for key, value in d.items():
if value == 1:
res["False"] = res.get("False", 0) + value
else:
res[key] = value
print(res)
{'asks': 2, 'False': 3, 'I': 2, 'Jim': 3, 'Like': 4, 'You': 2}
或使用collections.defaultdict
:
res = defaultdict(int)
for key, value in d.items():
if value == 1:
res["False"] += value
else:
res[key] = value
print(res)