user13888987
user13888987

Reputation:

Deleting keys from dictionary but adding the corresponding values

I'm trying to remove the repetitive items from Name and add its corresponding time to the Duration but it's much more challenging than I thought and couldn't find any solution for it on the web.

Duration = [
    10800, 
    1800, 
    1800, 
    3600, 
    3600, 
    3600
  ]
  
Name = [
    "Real Estate", 
    "ToDo", 
    "ToDo", 
    "Personal Finance", 
    "Website", 
    "Website"
  ]

Ideal results:

Duration = [
    10800, 
    3600, 
    3600, 
    7200 
  ]

Name = [
    "Real Estate", 
    "ToDo", 
    "Personal Finance", 
    "Website", 
  ]

I'm not sure what's the best way to it but I did:

I tried doing:

Data = dict(zip(Name,Duration))

for key, value in list(Data.items()):
      if key == key:
          Data.pop(key) and sum(value, value)

but I am getting:

TypeError: 'int' object is not iterable

and I'm not sure if that's even the way to go about adding the values.

Thanks :)

Upvotes: 0

Views: 36

Answers (2)

kevin-robb
kevin-robb

Reputation: 104

I would iterate through the indices of Name, storing the ones to delete, and then remove them at the end from both lists.

ind_to_remove = []
for i in range(1,len(Name)):
    # check if this name has already appeared
    if Name[i] in Name[0:i]:
        ind_to_remove.append(i)
# now remove them in descending order to preserve the correct index
for j in reversed(range(len(ind_to_remove))):
    del Name[ind_to_remove[j]]
    del Duration[ind_to_remove[j]]

You could instead remove them as you go, but this way ensures you won't get off on your indices.

Upvotes: 0

Grismar
Grismar

Reputation: 31339

I think this is what you need:

from collections import defaultdict

duration = [
    10800,
    1800,
    1800,
    3600,
    3600,
    3600
]

name = [
    "Real Estate",
    "ToDo",
    "ToDo",
    "Personal Finance",
    "Website",
    "Website"
]

result = defaultdict(int)
for n, d in zip(name, duration):
    result[n] += d

result_name = list(result.keys())
result_duration = list(result.values())

print(result_name, result_duration)

I've extracted the lists again because you suggested that's the required result, but perhaps the result dictionary is really all you're after.

The reason this works and is quite simple is because the defaultdict(int) allows you to start adding to an value in the dictionary, even if it hadn't been defined previously.

Upvotes: 1

Related Questions