Home > OS >  Exchange Key in a Python Dict File if Value in the Dict equals 1 and then counting them up to new Ke
Exchange Key in a Python Dict File if Value in the Dict equals 1 and then counting them up to new Ke

Time:12-13

I have a Dict file that looks like this:

"asks": 2,
"Hey": 1,
"I": 2,
"Jim": 3,
"Like": 4,
"Love": 1,
"she": 1,
"You": 2



I want to manipulate the Keys of the Values that == 1 to "False" and then add them up to a new value. So my Final Dict should look like this:

"asks": 2,
"False": 3,
"I": 2,
"Jim": 3,
"Like": 4,
"You": 2

CodePudding user response:

One approach:

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)

Output

{'asks': 2, 'False': 3, 'I': 2, 'Jim': 3, 'Like': 4, 'You': 2}

Or using a collections.defaultdict:

res = defaultdict(int)
for key, value in d.items():
    if value == 1:
        res["False"]  = value
    else:
        res[key] = value
print(res)
  • Related